CRTP是一种实现静态多态的技术(惯用法),免除了虚函数的使用。
直接看例子:
template <typename Derived>
class Base {
public:
void interface() {
// 调用了子类的implementation函数,且零开销
static_cast<Derived*>(this)->implementation();
}
void implementation() {
std::cout << "Default implementation in Base" << std::endl;
}
};
class Derived1 : public Base<Derived1> {
public:
void implementation() {
std::cout << "Custom implementation in Derived1" << std::endl;
}
};
class Derived2 : public Base<Derived2> {
// No custom implementation, so Base::implementation will be used.
};
int main() {
Derived1 d1;
d1.interface(); // Output: "Custom implementation in Derived1"
Derived2 d2;
d2.interface(); // Output: "Default implementation in Base"
return 0;
}