CRTP通过派生类继承自身作为模板参数的基类实现静态多态,编译期绑定函数调用,避免虚函数开销,适用于性能敏感场景如Eigen、Boost,常用于统一接口、混入模式与操作符重用,但不支持运行时多态且可能导致模板膨胀。

CRTP(Curiously Recurring Template Pattern),中文常称为“奇异的递归模板模式”,是C++中一种利用模板实现静态多态的经典技术。它通过让基类以派生类作为模板参数来继承自身,从而在编译期完成多态行为的绑定,避免了虚函数表带来的运行时开销。
CRTP的典型写法如下:
template <typename Derived>
class Base {
public:
void interface() {
static_cast<Derived*>(this)->implementation();
}
};
class Derived : public Base<Derived> {
public:
void implementation() {
// 具体实现
}
};
在这个结构中,Base 是一个类模板,接受一个类型参数 Derived,而 Derived 类继承自 Base<Derived>。这种“自己传给自己”的递归形式就是CRTP名称的由来。
CRTP的核心优势在于实现了静态多态,也就是在编译期决定调用哪个函数,而不是像虚函数那样在运行时通过vtable查找。
立即学习“C++免费学习笔记(深入)”;
当在基类中调用 static_cast<Derived*>(this)->implementation() 时,编译器已经知道 Derived 的具体类型,因此可以直接内联展开函数调用,提升性能。
与动态多态对比:
CRTP常用于以下几种情况:
示例:自动实现所有比较操作符
template <typename T>
class Comparable {
public:
bool operator!=(const T& other) const {
return !static_cast<const T*>(this)->operator==(other);
}
bool operator < (const T& other) const {
return static_cast<const T*>(this)->operator<(other);
}
// 可继续扩展其他操作符
};
class MyInt : public Comparable<MyInt> {
int value;
public:
bool operator==(const MyInt& other) const { return value == other.value; }
bool operator < (const MyInt& other) const { return value < other.value; }
};
这样,只要实现了 == 和 <,其他比较操作符就能自动获得。
CRTP虽然高效,但也有其局限性:
使用时要明确需求是否真的需要静态分发,若需运行时多态,仍应使用虚函数。
基本上就这些。CRTP是C++模板编程中的强大技巧,掌握它有助于写出高效且可复用的泛型代码。
以上就是c++++怎么使用CRTP(奇异的递归模板模式)_c++中CRTP静态多态实现原理解析的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号