mixin into every non-abstract subclass in D

92 views Asked by At

I have created a framework in witch each class deriving from Action needs to have some magic features like static methods etc. that depend on this class fields.

I am using a mixin template to achieve this:

mixin template ACTION(T:Action){

    static string url() {
        //in real code this is analysing fields of T class.
        return "foo";
    }

    //some other stuff

}

abstract class Action {

}

class FooAction : Action {

    mixin ACTION!(FooAction);

    //custom Foo methods

}

class BarAction : Action {

    mixin ACTION!(BarAction);

    //custom Bar methods

}

This works and is doing exactly what I need, however it is not completely DRY as I have to include mixin ACTION!(Subclass); in every non-abstract subclass. There is no case in witch I would like to have a subclass without this mixin.

So generally I ended up having something like Q_OBJECT macro from C++/Qt.

As D lang praises itself for being very dynamic, maybe there is a way to avoid this repetition and mixin this template into every subclass automatically?

So my code doing exactly the same could simply look like:

class FooAction : Action {

    //custom Foo methods

}

class BarAction : Action {

    //custom Bar methods

}
1

There are 1 answers

0
Adam D. Ruppe On BEST ANSWER

No. There's been requests to add a feature like that but right now there isn't one, you have to do the mixin yourself.

You can get kinda close if you are willing to modify the druntime source code, then you can make a meta object kind of thing accessible from the object via a pointer, a feature called RTInfo, but it still doesn't actually add code to the class itself (and of course, modifying druntime is a practical hassle).

So your current solution is probably the best one you have.