Feature request: __traits(canInstantiate), like __traits(compiles) but without suppressing syntax errors
schveiguy at gmail.com
Tue Jan 21 22:02:34 UTC 2020
On 1/18/20 10:21 AM, FeepingCreature wrote:
> 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)".
I don't see how that helps. isNumeric!T is ignoring the problem that X
is the wrong symbol name.
In the usage of foo, if I say if __traits(compiles, foo(5)) or
__traits(canInstantiate, foo, int), how does it know the error during
instantiation was not intended?
In other words, I need to know, was foo *intended* to compile with T,
not *does* it compile with T.
More information about the Digitalmars-d