DIPX: Enum Literals / Implicit Selector Expression

Timon Gehr timon.gehr at gmx.ch
Tue Jul 5 23:53:22 UTC 2022


On 7/1/22 21:37, Steven Schveighoffer wrote:
> On 7/1/22 2:32 PM, Walter Bright wrote:
>> On 7/1/2022 8:42 AM, Steven Schveighoffer wrote:
>>> How I would design it:
>>
>> Those are reasonable suggestions.
>>
>> But just let me throw this out. I've heard from many sources that 
>> nobody understands C++ function overloading. It is described with 
>> pages of detail in the Standard. Even compiler writers only 
>> *temporarily* understand it while they are implementing it.
>>
>> How C++ programmers deal with it is they randomly try things until it 
>> works.
> 
> This is why I'm asking the questions. I don't have experience on how to 
> implement function overloading, and I don't know what pitfalls might be 
> introduced from doing something like this.

I have implemented D's pretty simple function overloading rules in my 
experimental frontend. If you get a name clash you might get an 
ambiguity error, and other details are a consequence of the existing 
overloading rules, e.g.:

```d
import std;

alias Poly(T)=T delegate(T=T.init);
enum poly(string name)=q{
     (x){
         static if(is(typeof(typeof(x).%s)))
             return typeof(x).%s;
     }
}.format(name,name);

enum Foo{
     a,
     b,
}
enum Bar{
     b,
     c,
}

void fun(Poly!Foo foo, int x){ writeln(foo()); }
void fun(Poly!Bar bar, float x){ writeln(bar()); }

void main(){
     fun(mixin(poly!"b"), 1); // what does this do?
}
```

(Answer: It will call the first overload, because the lambda is 
considered a perfect match after type deduction.)

So I guess actually there is one open question: At what matching level 
should a polysemous enum literal match an enum type? If it's considered 
a perfect match, other parameters might cause a resolution of a name 
clash, if it's considered a match with implicit conversion, this does 
not happen.

Some may therefore prefer to consider it a match with implicit 
conversion so the compiler is more conservative and happier to deal out 
ambiguity errors. As different enum types are incompatible, you will 
never get a resolution because an overload is more specialized unless 
all matching overloads are with the same enum type.

In any case, everything is easily explained with the existing 
overloading rules plus one new definition of a matching level for 
polysemous enum literals. The pitfalls remain basically the same.


More information about the Digitalmars-d mailing list