多态的静态绑定(CRTP手法)

Curiously Recurring Template Pattern (CRTP手法)函数

原理很简单性能

经过模板函数 的强制转换调用子类同名函数,来模拟多态的动态绑定,实现和虚函数同样的功能,而且避免了动态绑定所带来的性能开销this

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;
}

虽然模拟了一部分场合的虚函数的功能,但也不能彻底替代虚函数来实现多态,由于这是模板,子类类型早已经决定了,有点相似语法糖code

相关文章
相关标签/搜索