Overloading based on attributes - is it a good idea?

Q. Schroll qs.il.paperinik at gmail.com
Thu May 30 15:30:26 UTC 2019


On Thursday, 30 May 2019 at 13:58:20 UTC, Exil wrote:
> I don't think it is that useful. Consider if you did do the 
> following:
>
>     void foo() nothrow;
>     void foo();
>
>     void bar() nothrow
>     {
>          foo(); // ok useful calls foo() nothrow
>     }
>
>     void ree()
>     {
>         foo(); // ambiguous can call both, should be an error
>     }
>
>
> It can call either function if the callee isn't nothrow. I 
> don't think it should implicitly call the function without the 
> nothrow either. It really varies on the situation which one 
> should be called, you may want the variant that doesn't throw 
> an exception. It would be surprising if you have a function 
> defined as nothrow, then add an overload without the nothrow 
> and now it is now calling a different overload in functions 
> without nothrow. At which point this isn't all that useful, it 
> will work as expected in nothrow functions but then you will 
> have to explicitly choose which one to use otherwise. Which is 
> basically the situation now with nothrow, you just have to use 
> a different function name.

I think is is orthogonal to how `const` is used on non-static 
member functions:

struct Example
{
     void member() const { }
     void member() /*mutable*/ { }
}

Example ex;
ex.member(); // calls mutable

It could call either function if the callee is mutable. People 
all over the board think it should implicitly call the function 
without the const. It could vary on the situation which one 
should be called, but mostly, you may want the variant that uses 
mutability to its advantage. Nobody finds it surprising if you 
have a const method, then add a mutable overload and now it is 
now calling a different overload in functions where the object is 
mutable.

You could handle mutable and const methods the same: Tell people 
they need different names. It just doesn't look so nice with 
operators (fixed names, you cannot choose another), type 
inference and meta-programming.

Nobody sees a problem with that, and it's about the same thing: 
The context of the call decides which overload is chosen. It is 
nothing new, C++ does it since the beginning.

As I see it, this is can be made into an argument for a 
`nothrow(some_ct_bool_value)` attribute.


More information about the Digitalmars-d mailing list