Overloading based on attributes - is it a good idea?

Walter Bright newshound2 at digitalmars.com
Tue May 28 17:27:08 UTC 2019


On 5/28/2019 9:08 AM, Andrei Alexandrescu wrote:
> int fun(int) pure;
> int fun(int);
> 
> pure int gun(int x)
> {
>     return fun(x);
> }
> 
> This doesn't work, but on the face of it it's not ambiguous - the second 
> overload of fun() would not compile anyway.
> 
> I was wondering whether allowing overloading on attributes in general would be a 
> good idea. I suspect templates and attribute deduction make that difficult.

More than difficult. I suspect it's impossible in the general case. D does 
inference of types and attributes from the bottom up, but this would be bottom 
up and top down. It's easy to know what to do for trivial cases, but for 
multiple levels and choices, that's graph theory that would be very complex to 
find a unique solution, and if a unique solution cannot be found, imagine the 
problems with informing the user just why.

It's like overloading based on return value:

   long fun(int);
   int fun(int);

   int gun(int x)
   {
      return fun(x);
   }

It's ambiguous even though the first overload of fun() would give an error.

Another consideration:

     class A { int fun() pure; }
     class B : A { overload int fun(); }

Because of covariance/contravariance, B.fun doesn't need to have the pure 
attribute added, the pureness is inherited from A.fun.


More information about the Digitalmars-d mailing list