开发者

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

开发者 https://www.devze.com 2022-12-25 16:12 出处:网络
Does C++ have a proper implementation of interface that does not use vtable? for example class BaseInterface{

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开发者_StackOverflow社区 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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号