Template Constraints
H. S. Teoh
hsteoh at quickfur.ath.cx
Sat Feb 24 04:25:38 UTC 2018
On Sat, Feb 24, 2018 at 02:54:13AM +0000, 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?
Yes:
void (T)(T t)
if (is(typeof(cast(int) T.init)))
{
...
}
Explanation:
- is(X) generally means "is X a valid type?". It's the usual way of
testing whether something is valid, because an invalid expression will
have no type, and is(X) will return false for it.
- To make use of is(X), generally you want to use typeof to extract the
type of some test expression.
- T.init is the usual D way of saying "give me an instance of type T",
because every type has an .init.
- Putting it together, we have our test object T.init, and our test
expression `cast(int) T.init`, extract the type of that using typeof,
and use the is(...) operator to test whether that type exists.
T
--
I think Debian's doing something wrong, `apt-get install pesticide', doesn't seem to remove the bugs on my system! -- Mike Dresser
More information about the Digitalmars-d-learn
mailing list