Container templates

Frustrated c1514843 at drdrb.com
Wed Feb 19 11:10:44 PST 2014


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).

In fact, I do want the first case because I will have multiple
arrays and need a way to add separation between them(the x does
that here) BUT the real problem is I need to hook into the add,
remove, etc to do things like validate.

e.g., programming challenge:

Create a class that contains two different arrays of type int and
type float that will restrict the int's to a range of 3 to 10 and
print a msg to the consol when a float larger than 1 is added or
removed from the float array.

a.myints.add(1); // asserts
a.myfloats.add(5); // prints msg to console

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.

The goal here is to do this in the minimum amount of work. I
don't want to have to recreate the array code every time I use
them in the class... and I don't want to inherit from a class or
use DI. e.g., templates should be the way to go. Just not sure
how to make it all work and if there are templates that work this
way(allow hooking into the methods).

I thought about using inner classes to add the separation:

class a
{
     class myints // : Array!int
     {
         mixin Array!int;
         // override void Add(int i) {}
     }
}

which I guess would work better if myints was a template.

Any ideas?


More information about the Digitalmars-d-learn mailing list