template this parameters for constructors

Gor Gyolchanyan gor.f.gyolchanyan at gmail.com
Wed Feb 20 06:37:40 PST 2013


Template this parameters (
http://dlang.org/template.html#TemplateThisParameter) are extremely useful
for writing generic methods in base classes or interfaces that need to know
the static type of the object they're called on.

class Base
{
    string label;

    this(string label_)
    {
        label = label_;
    }

    string toString(this This_)()
    {
        return This_.stringof ~ "(`" ~ label ~ "`)";
    }
}

class Derived: Base
{
    this()
    {
        super("Hello, world!");
    }
}

unittest
{
    Derived d = new Derived();
    assert(d.toString() == "Derived(`Hello, world!`)");
}

Of course, this wouldn't work if the toString() was called from a Base
reference, instead of Derived.

After I tested this, immediately thought of the constructor. The
constructor of the base class is guaranteed to be called when constructing
a derived class, right? Even if the call is implicit, it still happens and
at the call site the concrete type being constructed is known, so in
theory, a template this parameter on the base class's constructor should
allow the base class to know the static type of the object being
constructed (which is immensely useful for implementing dynamic dispatch
classes).

class Base
{
    this(this This_)()
    {
        // Build a dispatch table using __traits(allMethods, This_)
    }

    void opCall(Payload_)(Payload_ payload_)
    {
        // Dynamically dispatch payload_ using the previously built
dispatch table.
    }
}

class Derived: Base
{
    // implicitly generated constructor will call the Base.this() and
implicitly give it the static type of Derived.
}

unittest
{
    Base b = new Derived;
    b(); // 100% transparent dynamic dispatch
}

Unfortunately, this is what DMD had to say about this:

C:\Users\g.gyolchanyan\Desktop\test.d(3): Error: found 'This_' when
expecting ')'
C:\Users\g.gyolchanyan\Desktop\test.d(3): Error: semicolon expected
following function declaration
C:\Users\g.gyolchanyan\Desktop\test.d(3): Error: Declaration expected, not
')'

It looks like DMD thinks I was gonna write a postblit constructor and I
guess the functionality is already there, but can't be reached due to a
parsing error.

Is there any change of this being fixed any time soon?

-- 
Bye,
Gor Gyolchanyan.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20130220/43e2ac26/attachment-0001.html>


More information about the Digitalmars-d mailing list