CRTP(奇异的递归模板模式)

CRTP(Curiously Recurring Template Pattern),奇异的递归模板模式,指的是子类继承一个模板类,模板的特化类型是子类本身。

最简代码:

#include<iostream>
using namespace std;

template<typename T>
class Base
{
public:
    void virtualFunc()
    {
        static_cast<T*>(this)->realFunc();
    }
};

class Chird :public Base<Chird>
{
public:
    void realFunc()
    {
        cout << "real func";
    }
};

int main() 
{
    Chird().virtualFunc();
    return 0;
}

这个简单的例子就能看出CRTP的写法,也能看出,其实本质上静态多态。

CRTP的好处是,静态多态比继承虚函数的动态多态要快。

应用:

https://blog.csdn.net/nameofcsdn/article/details/121662411

猜你喜欢

转载自blog.csdn.net/nameofcsdn/article/details/121622654