Any trick for defining an operator overload in a different namespace?

Andrej Mitrovic andrej.mitrovich at gmail.com
Sat Aug 31 03:07:45 PDT 2013


I'm trying to achieve the syntax "opts[...] = 123", rather than using
the more direct "this[...] = 123". I can use this code:

-----
class C
{
    this()
    {
        opts = Opts(this);
        opts["foo"] = 1;
    }

    struct Opts
    {
        C c;

        void opIndexAssign(T)(T value, string option)
        {
            c.assign(option, value);
        }
    }

    Opts opts;

    private void assign(string option, int value)
    {
    }
}

void main()
{
    auto c = new C();
}
-----

But this explicitly stores the 'this' reference in the struct, I was
wondering if anyone knows of a trick to avoid having to do that. As
you can tell I just want a more convenient operator-based syntax over
calling the 'assign' method, but I don't want the operator to live in
the class space itself (because then I'd have to use "this[...] =
that", which is a little quirky for my taste).


More information about the Digitalmars-d-learn mailing list