Overloading based on attributes - is it a good idea?
Jonathan Marler
johnnymarler at gmail.com
Tue May 28 22:26:53 UTC 2019
On Tuesday, 28 May 2019 at 21:53:13 UTC, Manu wrote:
> On Tue, May 28, 2019 at 9:10 AM Andrei Alexandrescu via
> Digitalmars-d <digitalmars-d at puremagic.com> 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.
>
> I have wanted to overload on nothrow-ness before.
Yeah I could see some nice ways to select an implementation based
on nothrow.
struct CannotFail { bool failed() { return false; } }
struct CanFail { bool _failed; bool failed() { return _failed; } }
auto foo(bool mustBeNothrow)()
{
static if (mustBeNothrow)
{
// logic ...
return CanFail(true); // or CanFail(false);
}
else
{
if (foo!true().failed)
throw new Exception("an exception");
return CannotFail();
}
}
Now you can call foo from nothrow code or code that can throw.
If the return value follows the same api in both cases, you can
implement something like.
if (foo.failed)
{
// do something
// note: if this block can throw, then foo.failed will get
reduced to "false"
// so this whole block should be removed
}
More information about the Digitalmars-d
mailing list