On Thursday, 28 April 2016 at 10:21:34 UTC, Andrew Benton wrote:
So to the point: Is there an easier way to do this that I'm missing? Is there a language-design reason that mixed in templates can't inherit? It seems like an intuitive use of mixin.

Mixins are (mostly) just a convenient way to generate code, given some parameters. They aren't supposed to work any differently than the same code would if you instantiated the mixin by hand and inserted its contents at each usage site.

(I'll skip your example code here, since it has some problems and won't compile without significant changes.) The manual (mixin-free) code to do what you want looks like this:

class Base
{
    string writeName()
    {
        import std.uuid : randomUUID;
        return randomUUID.toString;
    }
}
class Inheritor : Base
{
    override string writeName()
    {
        return name;
    }
    string name = "test";
}

Doing this manually requires that some code be added to Inheritor. Using a mixin doesn't - and shouldn't - change this.

What a mixin could do for you in this situation, is consolidate duplicate code if there are many Inheritor classes:

mixin template WithName(string name0)
{
    override string writeName()
    {
        return name;
    }
    string name = name0;
}

class Inheritor1 : Base
{
    mixin WithName!"test1";
}
class Inheritor2 : Base
{
    mixin WithName!"test2";
}

Alternatively, you could just use inheritance (assuming that your needs can reasonably be expressed through single inheritance):

class NamedBase : Base
{
    override string writeName()
    {
        return name;
    }
    string name;

    this(string name0)
    {
        name = name0;
    }
}

class Inheritor3 : NamedBase
{
    this()
    {
        super("test3");
    }
}
class Inheritor4 : NamedBase
{
    this()
    {
        super("test4");
    }
}

Try it on DPaste: http://dpaste.dzfl.pl/5595bd09391f

Reply via email to