simple (I think) eponymous template question ... what is proper idimatic way ?

Ali Çehreli acehreli at yahoo.com
Tue Aug 17 18:28:38 UTC 2021


On 8/17/21 11:11 AM, james.p.leblanc wrote:

 > auto foo(T)(T a, T b) { ... }
 >
 > Now, suppose I need to restrict "T" only certain subsets of variable 
types.

There are template constraints:

import std.traits;

auto foo(T)(T a, T b)
if (isArray!T) {
   // ...
}

auto foo(T)(T a, T b)
if (isFloatingPoint!T)
{
   // ...
}

void main() {
   foo(1.5, 2.5);
}

See __traits as well and of course you can use any compile-time check in 
the template constraint.

 > I can imagine putting in some "static if" statements in my function body,

That method can display an intelligible error message if there is only 
one template implementation. Template constraints on the other hand, are 
not errors; they just determine what template implementations are 
available for instantiation for the used parameters.

And of course, 'static if' has more uses other than just error 
reporting; which might be performed better with 'static assert'.

Ali



More information about the Digitalmars-d-learn mailing list