Curiously recurring template pattern
是一种c++中常用的模式
在下面这个例子中,dog
和cat
都继承了base
类,base
类的interface
方法会将实际类型转换为子类并调用子类具体的实现
template <typename derived>
struct base {
void interface() {
static_cast<derived*>(this)->impl();
}
};
struct dog : base<dog> {
void impl() {
cout << "dog" << endl;
}
};
struct cat : base<cat> {
void impl() {
cout << "cat" << endl;
}
};
int main()
{
dog d;
d.interface(); // dog
cat c;
c.interface(); // cat
}