CRTP是一种使用了模板的方法,主要的好处是实现了静态多态,避免了虚函数造成的运行时开销。
静态多态
CRTP主要是通过模板,避免了虚函数的开销,具体如下
#include <iostream>
// CRTP基类
template<typename T>
class Base {
public:
void interface() {
static_cast<T*>(this)->implementation();
}
};
// 派生类
class Derived : public Base<Derived> {
public:
void implementation() {
std::cout << "Derived implementation" << std::endl;
}
};
int main() {
Derived d;
d.interface(); // 输出: Derived implementation
return 0;
}可以发现,这里没用虚函数,调用了基类中的方法,从而调用了implementation。虚函数的作用是通过虚表来在运行时确定应该调用的函数,而这里通过模板,将运行时的开销转到了编译期,通过编译期获得的类型信息,实现了多态。