templated function call from interface

TheFlyingFiddle theflyingfiddle at gmail.com
Sat Nov 16 15:29:39 PST 2013


On Saturday, 16 November 2013 at 08:42:05 UTC, rumbu wrote:
> I suppose that these two are related.
> Are these bugs or it's not possible to have templated functions 
> in an interface?

It is possible to define templates on interfaces however they 
have to be implemented in the interface using the 
Non-virtual-interface idiom.

//Non-virtual-interface idiom in general
interface IFoo
{
    final void bar()
    {
       baz();
       buz();
    }

    protected void baz();
    protected void buz();
}

This will ensure that both baz and buz will be called and in that 
order. To the outside the interface looks like it only exposes 
the bar method. Implementing classes provides implementation for 
baz and buz. This could be usefull if it is required to separate 
several things into methods but still be able to call then in a 
specific order.


You can do this.
interface IFoo2
{
    final void bar(T)(T t)
    {
       //Do something fun here.
    }

    //Some more protected / public methods here to be implemented.
}

I used this pattern myself when i did a small runtime reflection 
lib.

Now why can't you make templates in interfaces that can be 
implemented in subclasses?

interface I
{
    //Imho declaring a template without implementation in an 
interface
    //should be rejected by the compiler.
    void foo(T)(T t);
}

//Will give linker error if I.foo!atype is instantiated.
class C : I { }

//Will give linker error if I.foo!atype is instantiated through 
an instance of I
//But works if called through an instance of D.
class D : I
{
    void foo(T)(T t)
    {
       //Impl
    }
}

The class D seems like it should work but it dosn't and why is 
that?

The reason is that the compiler has no idea how to build a 
virtual function table for _I_. A function template is NOT a 
function it is simply a blueprint of a function. When a function 
template gets instantiated a function is created from that 
blueprint. So how is the compiler supposed to know what functions 
that should be in the virtual function table when there is only a 
blueprint to go on? The number of instantiations can vary and 
worse they could be instantiatied in a diffrent module. So the 
vtable would have to be decided after the compiler has figured 
out all possible instantiations. This still would not work since 
a template can have diffrent instantiations in diffrent DLL's.

I hope this helped.



-- TFF


More information about the Digitalmars-d-learn mailing list