Halo
发布于 2022-05-16 / 146 阅读 / 0 评论 / 0 点赞

CRTP奇异递归模板模式

CRTP

CRTP全称是 curious recurring template pattern,是一种c的设计模式,精巧地结合了继承和模板编程的技术。
可以用来给c
的class提供额外功能、实现静态多态等。

多态

#include <iostream>
 
template <class Derived>
struct Base { void name() { (static_cast<Derived*>(this))->impl(); } };
 
struct D1 : public Base<D1> { void impl() { std::cout << "D1::impl()\n"; } };
struct D2 : public Base<D2> { void impl() { std::cout << "D2::impl()\n"; } };
 
int main()
{
    Base<D1> b1; b1.name();
    Base<D2> b2; b2.name();
 
    D1 d1; d1.name();
    D2 d2; d2.name();
}

输出:

D1::impl()
D2::impl()
D1::impl()
D2::impl()

继承父类功能

#include <iostream>
#include <string_view>
 
template <class Derived>
struct Base {
public:
    printType() const{
        std::string_view name = typeid(Derived).name();
        std::cout << name.substr(pos:1, n:name.size()-1) << "\n";
    }
};
 
struct D1 : public Base<D1> {}; // D1 实例化
struct D2 : public Base<D2> {};
 
int main()
{
    Base<D1> b1; b1.printType();
    Base<D2> b2; b2.printType();
}

以PrintType实现为例,模板类的成员函数只有在用到的时候才会实例化,比如D1实例话,而这时Derived1已经是一个完整的class类型了。


评论