On Wednesday, 19 February 2014 at 19:44:12 UTC, Meta wrote:
On Wednesday, 19 February 2014 at 19:10:44 UTC, Frustrated wrote:
Are there container templates that one can mixin to classes that
give them container behavior?

e.g.,

instead of

class A
{
    Array!int x;
}

I want

class A
{
   mixin Array!int;
}

so that I can do something like a.Add(3) instead of a.x.Add(3).

One solution is to use alias this.

class A
{
    Array!int x;
    alias x this;
}

Then you can do a.Add(3) and the method call will be "rewritten" (I don't know if it's *actually* rewritten) as a.x.Add(3).

myints nor myfloats need to be actual elements of the class. In
fact, in this case it might be ok to override them, e.g.,
a.add(1) and a.add(5f) above.

This throws a wrench into the above solution, as you can currently only have 1 alias this. However, your idea of inner classes would work, I think.

I played around with it a bit at work and this is a workable solution:

import std.container;

class A
{
        this()
        {
                myints = new MyInts();
                myfloats = new MyFloats();
        }
        
        MyInts myints;
        MyFloats myfloats;
        
        private static
        {
                class MyInts
                {
                        Array!int x;
                        alias x this;
                }
                
                class MyFloats
                {
                        Array!float x;
                        alias x this;
                }
        }
}

void main()
{
        auto a = new A();
        a.myints.insert(3);
        a.myfloats.insert(3);
}

Reply via email to