How to ensure that pattern type is scalar in D?

I have two functions: one is scalar multiplication for vector and the other is vector-matrix multiplication:

pure T[] mul(S, T)(S s, T[] a) 

and

 pure T[] mul(T)(T[] a, T[][] B) 

Of course, this leads to conflict, because S can be a vector, so the first pattern covers the second. How to tell the compiler, I want only the scalar type to be S ?

+6
source share
1 answer

You need to use a template constraint .

 pure T[] mul(S, T)(S s, T[] a) if (isScalarType!S) 

This declares that the pattern should be considered only when isScalarType!S is true .

isScalarType can be found in std.traits .

In D, scalar types are numeric types, character types, and bool . You can limit the further use of other features from std.traits if you wish (for example, isNumeric or isFloatingPoint ).

+10
source

Source: https://habr.com/ru/post/955350/


All Articles