Curiously Recurring Template Pattern(CRTP 手法)是一种利用模板机制实现静态多态的 C++ 惯用法。

其原理很简单:通过模板函数中的强制类型转换,调用子类的同名函数,从而模拟多态的动态绑定,实现与虚函数相同的功能,同时避免了动态绑定带来的性能开销。

template <class T>
class A
{
public:
	void func(){ ((T*)this)->funcImpl(); };
	void funcImpl(){}
};

class B:public A<B>
{
public:
	void funcImpl(){ cout << __FUNCTION__ << endl; }
};



int main(int argc, char *argv[])
{

	A<B> *a = new B;
	a->func();

	system("pause");
	return 0;
}

CRTP 虽然能在部分场合模拟虚函数的功能,但无法完全替代虚函数来实现多态。原因在于它基于模板,子类的类型在编译期就已经确定,有点类似于语法糖。