On Tuesday, 13 June 2017 at 11:36:45 UTC, Steven Schveighoffer wrote:

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

Is it possible for the `result` variable in the following code to be returned as an immutable type if it's created by adding two immutable types?

import std.stdio;

struct Rational
{
        public long numerator;
        public long denominator;

public inout Rational opBinary(string op)(inout(Rational) other) const
        {
                static if (op == "+")
                {
                        return inout(Rational)(0, 0);
                }
                else
                {
                        static assert(0, "Operator '" ~ op ~ "' not 
implemented");
                }
        }
}

unittest
{
        auto baz    = immutable(Rational)(1, 3);
        auto qux    = immutable(Rational)(1, 6);
        auto result = baz + qux;

        writeln(typeof(result).stringof); // Result is not immutable!
}

Reply via email to