The One With D News and Opinions of the Digital Mars D Programming Language

17Jun/060

More on Policies

A limitation that I quickly ran into with my attempt at templated, inherited policies was D's lack of support for multiple inheritance. Normally, I have no need for MI, but this is one case where it would have been neat to have. As long as a class uses one policy, the templated, inherited approach is good enough. To solve the multiple policy problem, I went with templated containment:


import std.stdio;
class Host(G, M)
{
    G g;
    M m;

    void doSomething()
    {
        g.foo();
        m.bar();
    }
} 

class GreetPolicy
{
    void foo()  { writefln("Hello World!"); }
}

class MeetPolicy
{
    void bar() { writefln("Nice to meet you!"); }
}

void main()
{
    Host!(GreetPolicy, MeetPolicy) h = new Host!(GreetPolicy, MeetPolicy);
    h.doSomething();

    Host!(GreetPolicy, MeetPolicy) h2 =
        new Host!(GreetPolicy, MeetPolicy)(new GreetPolicy(), new MeetPolicy());
    h2.doSomething();
}

By using two constructors in the template, policies which require constructor args can still be used. The only drawback to this over the inheritance model is that the host does not inehrit the interface of the policies. The inheritance approach is pretty powerful in that regard. With the inheritance form of the template, if the host expects the policy to implement one non-private method but the policy actually implements more, the host inherits all of those methods as well. If there's a way to mimic that with templated containment, I haven't figured it out yet. Maybe someone else has?

Technorati Tags: , , ,