Thread overview |
---|
July 04, 2017 safe method overloading with different refness of its arguments | ||||
---|---|---|---|---|
| ||||
``` struct Foo { ubyte width, length; // by reference bool opEquals(ref const(Foo) other) const pure @safe { if (width != other.width) return false; if (length != other.length) return false; return true; } // by value bool opEquals(const(Foo) other) const pure @safe { return opEquals(other); } } ``` It works for me, but I'm curious - will compiler always recognize what to call and I can avoid recursion and stack overflow or I shouldn't do so? |
July 04, 2017 Re: safe method overloading with different refness of its arguments | ||||
---|---|---|---|---|
| ||||
Posted in reply to drug | On Tuesday, 4 July 2017 at 10:40:42 UTC, drug wrote:
> ```
> struct Foo
> {
> ubyte width, length;
>
> // by reference
> bool opEquals(ref const(Foo) other) const pure @safe
> {
> if (width != other.width)
> return false;
> if (length != other.length)
> return false;
> return true;
> }
>
> // by value
> bool opEquals(const(Foo) other) const pure @safe
> {
> return opEquals(other);
> }
> }
> ```
>
> It works for me, but I'm curious - will compiler always recognize what to call and I can avoid recursion and stack overflow or I shouldn't do so?
No, not always. One out of two hundreds the compiler fails to recognize the right call.
Jokes aside if you're not sure just use a templated function with `auto ref` parameter.
|
July 04, 2017 Re: safe method overloading with different refness of its arguments | ||||
---|---|---|---|---|
| ||||
Posted in reply to Basile B. | 04.07.2017 15:06, Basile B. пишет:
> On Tuesday, 4 July 2017 at 10:40:42 UTC, drug wrote:
>> ```
>> struct Foo
>> {
>> ubyte width, length;
>>
>> // by reference
>> bool opEquals(ref const(Foo) other) const pure @safe
>> {
>> if (width != other.width)
>> return false;
>> if (length != other.length)
>> return false;
>> return true;
>> }
>>
>> // by value
>> bool opEquals(const(Foo) other) const pure @safe
>> {
>> return opEquals(other);
>> }
>> }
>> ```
>>
>> It works for me, but I'm curious - will compiler always recognize what
>> to call and I can avoid recursion and stack overflow or I shouldn't do
>> so?
>
> No, not always. One out of two hundreds the compiler fails to recognize
> the right call.
> Jokes aside if you're not sure just use a templated function with `auto
> ref` parameter.
Thank you for the hint. It works and even tests pass)
|
Copyright © 1999-2021 by the D Language Foundation