template this parameters for constructors

Jacob Carlborg doob at me.com
Wed Feb 20 06:42:54 PST 2013


On 2013-02-20 15:37, Gor Gyolchanyan wrote:

> 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.

I haven't even thought about this use case. It would be so cool.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list