Generic operator overloading for immutable types?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 13 04:36:45 PDT 2017


On 6/12/17 3:36 PM, H. S. Teoh via Digitalmars-d-learn wrote:
> On Mon, Jun 12, 2017 at 07:38:44PM +0000, Gary Willoughby via Digitalmars-d-learn wrote:
>> In the following code is there any way to make the `opBinary` method
>> generic to be able to accept immutable as well as a standard type? The
>> code currently passes the unit test but I wonder if I could get rid of
>> the duplication to overload the operator? I'm failing badly.
>
> This is what inout was designed for:
>
>  	public inout Rational opBinary(string op)(inout Rational rhs)
>  	{
>  		static if (op == "+")
>  		{
>  			return inout(Rational)(0, 0);
>  		}
>  		else
>  		{
>  			static assert(0, "Operator '" ~ op ~ "' not implemented");
>  		}
>  	}
>
> That should do the trick.

Nope, const works just fine. A clue is in your return type -- it's not 
inout!

This should work:

public Rational opBinary(string op)(Rational rhs) const

If Rational had any indirections, then inout would be required, and your 
signature wouldn't work (because you can't convert an 
inout(SomethingWithPointers) to SomethingWithPointers).

Why do I need to make the member function const, but not the parameter? 
Because the parameter is taken by value, 'this' is a reference.

-Steve


More information about the Digitalmars-d-learn mailing list