Defining some stuff for each class in turn

Jarrett Billingsley jarrett.billingsley at gmail.com
Thu Oct 1 10:19:18 PDT 2009


On Thu, Oct 1, 2009 at 12:25 PM, Andrei Alexandrescu
<SeeWebsiteForEmail at erdani.org> wrote:
> I am becoming increasingly aware that we need to provide some means to
> define certain members (data and functions) for each class as if they were
> pasted there.
>
> Right now that right is reserved to the compiler, which generates e.g. one
> static classinfo object for each class. But users would want to also define
> members for each class automatically. This is often the case with
> contravariant-argument functions (that we discussed recently) and other
> important cases such as factories and cloning.
>
> For starters, assume I want to define one static int for each class in a
> hierarchy.
>
> class Counted {
>    static uint counter;
>    ...
> }
>
> Then subclasses of Counted would all share counter, something I don't want.
> I want each subclass to have its own counter, so I need to ask derived
> classes to *also* define counter:
>
> class A : Counted {
>    static uint counter;
>    ...
> }
>
> With the suggested feature, there would be the ability to define counter
>  for each class in turn.
>
> class Counted {
>    mixin(Derived)
>    {
>        // Insert here stuff that must be "pasted" for each subclass
>        // of Counted (including Counted itself).
>        // Use "Derived" as the name of the current subtype of Counter
>        static uint counter;
>        static if (is(Counted == Derived))
>            ref uint getCounter() { return counter; }
>        else
>            override ref uint getCounter() { return counter; }
>    }
>    ...
> }
>
> The code above does something quite neat - it defines an overridable
> function Counted.getCounter in the base class, and then overrides it in
> *every* class inheriting that base class, to return that class' own counter.
>
> The same should go in interface definitions - the feature should allow you
> to
>
> There are quite a few immediate applications of this: opEquals, opCmp,
> clone, various factories and object pools, and most importantly reflection.
> To enable custom reflection with today's D, we'd have to require each class
> to insert some code inside the class body. With the mechanism described
> above, we allow the base class or an interface (e.g. Reflectable) to inject
> the code into the derived class' body.
>
> What do you think?

I think it sounds interesting enough, but I can't help but wonder if
this is a feature that you've really thought through (especially wrt.
how it interacts with mechanisms such as template mixins and normal
symbol inheritance), or if you just want it to support some pattern
you want to use in Phobos 2.



More information about the Digitalmars-d mailing list