Template Constraints

Adam D. Ruppe destructionator at gmail.com
Sat Feb 24 03:04:07 UTC 2018


On Saturday, 24 February 2018 at 02:54:13 UTC, Jonathan wrote:
> I am having trouble finding many useful explanations of using 
> template constraints beyond basic usage.

The constraint is just like static if as to what it allows 
inside, so you can check almost anything in there.

Like for the cast, you might do

void name(T)(T t) if(__traits(compiles, cast(int) t) {}

just seeing it the cast compiles.

You might also do

if(is(T : int))

which asks if T is implicitly convertible to int. But since you 
want explicit cast, the compiles is prolly the way to go.

is: https://dlang.org/spec/expression.html#IsExpression
compiles: https://dlang.org/spec/traits.html#compiles


More information about the Digitalmars-d-learn mailing list