Feature request: __traits(canInstantiate), like __traits(compiles) but without suppressing syntax errors

FeepingCreature feepingcreature at gmail.com
Sat Jan 18 15:21:47 UTC 2020


On Friday, 17 January 2020 at 16:01:29 UTC, Steven Schveighoffer 
wrote:
> However, the real problem is things like typos that cause the 
> function not to compile for reasons other than the intended 
> failures.
>
> For example:
>
> T foo(T)(T x)
> {
>    return X + 5; // typo on parameter name
> }
>
> This will NEVER compile, because X will never exist. The 
> intention was for it to compile with types that support 
> addition to integers (i.e. it's EXPECTED to fail for strings), 
> but instead it fails for all types. The result is that your 
> code selects some other path when you don't want it to. 
> Sometimes this just means it works but is slower, which is even 
> harder to figure out.
>
> But it's hard for the compiler to deduce intention from such 
> typos. It would be great if the compiler could figure out this 
> type of error, but I don't think it can.
>

Yes it can!

D already has support for exactly this kind of thing, with 
std.traits and `if()` constraints. If you have a metafunction 
that tries to see if "an alias is usable with string", and it 
checks that with __traits(canInstantiateCall, foo, string.init) 
or whatever, then you *should* get a syntax error even in the 
"return x + 5" case. If you want to avoid that, we don't need 
language changes, you just need to use the *already existing* 
mechanism of "if (isNumeric!T)".


More information about the Digitalmars-d mailing list