Container templates
Frustrated
c1514843 at drdrb.com
Wed Feb 19 12:38:21 PST 2014
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.
yeah, I basically want to avoid typing a lot and reuse code. I
could create a template that is essentially all the code from
your standard container object(probably just rename class to
template) and mix it in. The problem is that there will be a lot
of methods in the class... probably not a real issue. I could use
the types directly. Not sure, though, the benefit of using
templates over inheritance/inner classes.
Just trying to avoid a lot of typing and have an efficient
solution. I have several classes with array inside them and I
want to convert them so that I can add "hooks" later(do stuff
when elements are added/etc easily... without the overhead of
delegates or events that one might normally use for RT behavior).
templates seem like the solution but now sure if there such an
array/container already exists so I can "plug and play".
More information about the Digitalmars-d-learn
mailing list