CRTP避免虚拟成员函数开销 [英] CRTP to avoid virtual member function overhead

查看:146
本文介绍了CRTP避免虚拟成员函数开销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++:CRTP以避免动态多态性中,以下解决方案建议避免虚拟成员函数的开销,并强加一个特定的接口:

In C++: CRTP to avoid dynamic polymorphism, the following solution is proposed to avoid the overhead of virtual member functions and impose a specific interface:

template <class Derived>
struct base {
  void foo() {
    static_cast<Derived *>(this)->foo();
  };
};

struct my_type : base<my_type> {
  void foo() {}; // required to compile. < Don't see why
};

struct your_type : base<your_type> {
  void foo() {}; // required to compile. < Don't see why
};

但是似乎派生类不需要一个定义来编译,因为它继承了一个编译精细,而不定义my_type :: foo)。事实上,如果提供了一个函数,当使用派生类时不会调用基函数。

However it seems that the derived class does not require a definition to compile as it inherits one (the code compiles fine without defining a my_type::foo). In fact if a function is provided, the base function will not be called when using the derived class.

所以问题是,下面的代码替换可以接受?):

So the question is, is the following code replacement acceptable (and standard?):

template <class Derived>
struct base {
  void foo() {
    // Generate a meaningful error if called
    (void)sizeof( Derived::foo_IS_MISSING );
  };
};

struct my_type : base<my_type> {
  void foo() {}; // required to compile.
};

struct your_type : base<your_type> {
  void foo() {}; // required to compile.
};

int main() {
  my_type my_obj;
  my_obj.foo(); // will fail if foo missing in derived class
}


推荐答案

这个模式的重点是,据我所知,你可以传递参数简单为 template< typename T&基底< T> & ,并且您的界面由 base< T> 中的(非虚拟)函数定义。如果你没有一个界面,你想定义(正如你在你的问题的第二部分建议),那么就没有必要首先这样做。

The whole point of this pattern is, as far as I understand, that you can pass arguments simply as template <typename T> base<T> & and your interface is defined by (non-virtual) functions in base<T>. If you don't have an interface that you want to define (as you are suggesting in the second part of your question), then there's no need for any of this in the first place.

请注意,你不是强加一个接口,就像纯虚拟函数,而是你提供一个接口。因为一切都在编译时解决,强加不是这么强的要求。

Note that you are not "imposing" an interface like with pure virtual functions, but rather you are providing an interface. Since everything is resolved at compile time, "imposing" isn't such a strong requirement.

这篇关于CRTP避免虚拟成员函数开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆