CRTP避免动态多态性 [英] CRTP to avoid dynamic polymorphism
问题描述
如何在C ++中使用CRTP以避免虚拟成员函数的开销?
有两种方法。 / p>
第一个是通过静态指定类型结构的接口:
template< class Derived>
struct base {
void foo(){
static_cast< Derived *>(this) - > foo
};
};
struct my_type:base< my_type> {
void foo(); //需要编译。
};
struct your_type:base< your_type> {
void foo(); //需要编译。
};
第二个是避免使用引用到基址或指针到基址成语和在编译时做接线。使用上面的定义,你可以有如下模板函数:
template< class T& // T在编译时间推导
void bar(base< T& obj){
obj.foo(); //将静态分派
}
struct not_derived_from_base {}; // notice,not derived from base
// ...
my_type my_instance;
your_type your_instance;
not_derived_from_base invalid_instance;
bar(my_instance); //将调用my_instance.foo()
bar(your_instance); //将调用your_instance.foo()
bar(invalid_instance); //编译错误,无法推导出正确的重载
因此结合结构/接口定义和编译时类型扣除在你的函数允许你做静态调度而不是动态调度。这是静态多态性的本质。
How can I use CRTP in C++ to avoid the overhead of virtual member functions?
There are two ways.
The first one is by specifying the interface statically for the structure of types:
template <class Derived>
struct base {
void foo() {
static_cast<Derived *>(this)->foo();
};
};
struct my_type : base<my_type> {
void foo(); // required to compile.
};
struct your_type : base<your_type> {
void foo(); // required to compile.
};
The second one is by avoiding the use of the reference-to-base or pointer-to-base idiom and do the wiring at compile-time. Using the above definition, you can have template functions that look like these:
template <class T> // T is deduced at compile-time
void bar(base<T> & obj) {
obj.foo(); // will do static dispatch
}
struct not_derived_from_base { }; // notice, not derived from base
// ...
my_type my_instance;
your_type your_instance;
not_derived_from_base invalid_instance;
bar(my_instance); // will call my_instance.foo()
bar(your_instance); // will call your_instance.foo()
bar(invalid_instance); // compile error, cannot deduce correct overload
So combining the structure/interface definition and the compile-time type deduction in your functions allows you to do static dispatch instead of dynamic dispatch. This is the essence of static polymorphism.
这篇关于CRTP避免动态多态性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!