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.

import std.stdio;

struct Rational
{
        public long numerator;
        public long denominator;

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

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

unittest
{
        auto foo = Rational(1, 3);
        auto bar = Rational(1, 6);
        writefln("%s", foo + bar);

        auto baz = immutable Rational(1, 3);
        auto qux = immutable Rational(1, 6);
        writefln("%s", baz + qux);
}

Reply via email to