Search code examples
c++interfacevtablestatic-polymorphism

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


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.


Solution

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