Feature request: __traits(canInstantiate), like __traits(compiles) but without suppressing syntax errors
Petar
Petar
Fri Jan 17 15:34:44 UTC 2020
On Friday, 17 January 2020 at 14:57:27 UTC, Steven Schveighoffer
wrote:
> On 1/17/20 12:54 AM, FeepingCreature wrote:
>>
>> Would be nice, but would be a hard spec change. This is the
>> sort of thing that D should have been doing from the
>> beginning, but we may be too far in now for __traits(compiles)
>> to be changed to do this. However, this is the behavior I
>> would ask for for __traits(canInstantiateWith).
>>
>
> Just to point you at my previous thread on this:
> https://forum.dlang.org/post/q1jequ$r63$1@digitalmars.com
>
> I think more tools for diagnosing why something doesn't happen
> would be good, but the request of "tell me if I was stupid" is
> I think impossible for the compiler to figure out.
>
> -Steve
In other languages, such as C#, TypeScript and Rust, generic
functions can use only properties of generic types iff such
properties were required in the function generic type
constraints. AFAIK Nim's Concepts [1] are also moving in that
direction, even though their current way is more similar to D (I
chatted with one of their core developers, a couple of months ago
at a conference, but I may be misremembering some details).
In other words:
void use(T)(T obj)
where (hasMethod!(T, "callMe", int function(string, bool)))
{
int x = obj.callMe("hello", true); // this works
// the following would cause the template definition to
// fail to type check (before even being instantiated):
// obj.someThingElse = 3;
}
Of course, requiring complete constraints for D templates would
be quite controversial, (although many languages are able to get
away with that), but I think it could be a good if we could
opt-into that on a per function basis (e.g. using `where`,
instead of `if`).
If D has such a feature, I believe that libraries like phobos
would use it extensively, while user (app) code would use current
template duck typing model and only opt-into a stronger model
when a developer wants to debug why his template code doesn't
work as expected.
[1]: https://nim-lang.org/docs/manual_experimental.html#concepts
More information about the Digitalmars-d
mailing list