Showing a user specified error message when no overloads match

monarch_dodra via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 27 05:35:22 PDT 2014


On Sunday, 27 July 2014 at 08:40:42 UTC, Marc Schütz wrote:
> On Sunday, 27 July 2014 at 00:43:40 UTC, H. S. Teoh via 
> Digitalmars-d-learn wrote:
>> On Sat, Jul 26, 2014 at 05:14:44PM +0000, via 
>> Digitalmars-d-learn wrote:
>>> Hmmm... thinking about it, is this possible?
>>> 
>>> 1. Remove the constraints to match anything.
>>> 2. Inside the template, have some construct that enumerates 
>>> all possible
>>> overloads and UFCS functions that are visible at the point of 
>>> instantiation.
>>> 3. If this set contains only the current template, use a 
>>> static assert
>>> to print the message.
>>> 4. Otherwise, make the template fail to compile somehow (for 
>>> example,
>>> evaluate a semantically invalid expression), and hope that the
>>> compiler will then take the other overloads into consideration
>>> (SFINAE).
>>> 
>>> Could this work?
>>
>> D does not have SFINAE.
>
> http://dlang.org/templates-revisited.html says otherwise.
>
> But thinking about it, I've never seen it used anywhere, nor 
> used it myself, and even the examples in the linked article 
> under the SFINAE section use `is` expressions instead...

It's poorly worded: "is" is what functionally replaces the SFINAE 
functionality.

>>
>> This has been discussed before. I proposed the following 
>> solution:
>>
>> - Sig constraints should match all types that the function 
>> *logically*
>>  accepts -- even if the current implementation does not 
>> support some of
>>  said types.
>>
>> - In the function body, use a `static if` chain to implement
>>  specializations.
>>
>> - In the final else clause, do a static assert(0) with a 
>> user-friendly
>>  error message.
>
> But this prevents other people from providing overloads in 
> their own modules :-(

Not quite: It prevents users from providing "un-ambigous" 
overloads. But arguably, it's a good thing.

I've argued before against the "over use" of template constraints 
for type validation. Their initial use was really to restrict the 
"logical types" that can be used, and help with template 
overload. Not for validation. If the type then has some "flaw", 
that's where the static ifs come in.

This as a several advantages:
- Cleaner interface (*cough* 
http://dlang.org/phobos/std_algorithm.html#sort *cough*)
- Better error messages in case of non match ("The provided range 
can not be stable sorted, because its elements are not lvalues").
- Prevents "overload" turning into a hijack. You can add your 
overload (without ambiguity) if it works on types completely 
un-related. That won't be ambiguous. But if you are adding a very 
specific variant, it might be better that your function can't be 
accidentally called, and create surprises later.


More information about the Digitalmars-d-learn mailing list