Template Constraints

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Feb 24 03:05:16 UTC 2018


On Saturday, February 24, 2018 02:54:13 Jonathan via Digitalmars-d-learn 
wrote:
> I am having trouble finding many useful explanations of using
> template constraints beyond basic usage.
>
> I would like to have a template constrant to enforce that a type
> can be explicitly cast to another type:
>
>      void (T)(T t)
>              if (cast(int) T)//force `cast(int) T` to be possible
>          {
>              // Yay I know `t` can be cast to an `int`!
>      }
>
> Is this possible?

Well, template constraints in general usually either test that the type of
one expression matches another or that a particular piece of code compiles.
So, you'd need to test that the cast compiles. That requires either an is
expression or __traits(compiles, ...) (or an eponymous template that
contains such an expression). In this case, you could probably just do

    if(is(typeof(cast(int)t)))

since as long as the result of the expression isn't void, the is expression
will be true.

And note that the expression uses t, not T. You can't cast the type itself.
You have to cast a value of that type.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list