On Saturday, February 24, 2018 02:54:13 Jonathan via Digitalmars-d-learn 
> 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


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

Reply via email to