views:

168

answers:

2

Does C++ have a proper implementation of interface that does not use vtable?

for example

class BaseInterface{
public:
virtual void func() const = 0;
}

class BaseInterfaceImpl:public BaseInterface{
public:
void func(){ std::cout<<"called."<<endl; }
}

BaseInterface* obj = new BaseInterfaceImpl();
obj->func();

the call to func at the last line goes to vtable to find the func ptr of BaseInterfaceImpl::func, but is there any C++ way to do that directly as the BaseInterfaceImpl is not subclassed from any other class besides the pure interface class BaseInterface?

Thanks. Gil.

+6  A: 

Yes. It goes by the moniker CRTP. Have a gander.

wheaties
In particular, the heading "Static polymorphism": http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism Maybe you could edit that example into your answer?
Thomas
@Thomas: thanks. ed.
gilbertc
No problem. I'm quite curious, your code is that optimized where even the small overhead of a vtable look-up is hurting performance? What application? Normally it's used as a space saver or in an implementation of RAII concern.
wheaties
A: 

I think in any language, it's going to have to go to some equivalent of a vtable in order to do dynamic dispatch unless it knows at compile time what function needs to be called. This could be the result of a clever compiler optimization, or a technique such as CRTP (which wheaties already mentioned).

rmeador
and by the way, I am unable to understand what about going through the vtable makes such a call "improper".
rmeador
@thomas, rmeador: agreed that i shouldn't use the word proper. should be along the direction of 'more efficient' and 'light' implementation of interface.
gilbertc