当前位置: 首页 > news >正文

C++CRTP奇异递归模板

C++CRTP奇异递归模板

奇异递归模板模式(CRTP)是派生类将自己作为模板参数传递给基类的技术。CRTP实现静态多态,避免了虚函数的运行时开销。

CRTP的基本形式:基类模板接受派生类作为参数。

#include
#include

template
class Base {
public:
void interface() {
static_cast(this)->implementation();
}

static void static_interface() {
Derived::static_implementation();
}

Derived& derived() {
return static_cast(*this);
}

const Derived& derived() const {
return static_cast(*this);
}
};

class DerivedA : public Base {
public:
void implementation() {
std::cout << "DerivedA implementation\n";
}

static void static_implementation() {
std::cout << "DerivedA static\n";
}
};

class DerivedB : public Base {
public:
void implementation() {
std::cout << "DerivedB implementation\n";
}

static void static_implementation() {
std::cout << "DerivedB static\n";
}
};

void crtp_basic() {
DerivedA a;
DerivedB b;

a.interface();
b.interface();

Base::static_interface();
Base::static_interface();
}

CRTP实现对象计数。

template
class ObjectCounter {
static inline int count_ = 0;
static inline int alive_ = 0;

protected:
ObjectCounter() {
++count_;
++alive_;
}

~ObjectCounter() {
--alive_;
}

public:
static int total_created() { return count_; }
static int currently_alive() { return alive_; }
};

class Widget : public ObjectCounter {
int id_;
public:
Widget(int id) : id_(id) {}
int id() const { return id_; }
};

void object_counter_demo() {
std::cout << "Initial: " << Widget::currently_alive() << "\n";

{
Widget w1(1);
Widget w2(2);
std::cout << "Two created: " << Widget::currently_alive() << "\n";
std::cout << "Total created: " << Widget::total_created() << "\n";
}

std::cout << "After scope: " << Widget::currently_alive() << "\n";
}

CRTP实现比较运算符。

template
class EqualComparable {
public:
friend bool operator==(const Derived& a, const Derived& b) {
return a.equal_to(b);
}

friend bool operator!=(const Derived& a, const Derived& b) {
return !a.equal_to(b);
}
};

template
class Comparable : public EqualComparable {
public:
friend bool operator<(const Derived& a, const Derived& b) {
return a.less_than(b);
}

friend bool operator>(const Derived& a, const Derived& b) {
return b.less_than(a);
}

friend bool operator<=(const Derived& a, const Derived& b) {
return !b.less_than(a);
}

friend bool operator>=(const Derived& a, const Derived& b) {
return !a.less_than(b);
}
};

class Point : public Comparable {
int x_, y_;
public:
Point(int x, int y) : x_(x), y_(y) {}

bool equal_to(const Point& other) const {
return x_ == other.x_ && y_ == other.y_;
}

bool less_than(const Point& other) const {
if (x_ != other.x_) return x_ < other.x_;
return y_ < other.y_;
}

friend std::ostream& operator<<(std::ostream& os, const Point& p) {
os << "(" << p.x_ << "," << p.y_ << ")";
return os;
}
};

void comparable_demo() {
Point p1(1, 2), p2(1, 2), p3(3, 4);

std::cout << p1 << " == " << p2 << ": " << (p1 == p2) << "\n";
std::cout << p1 << " != " << p3 << ": " << (p1 != p3) << "\n";
std::cout << p1 << " < " << p3 << ": " << (p1 < p3) << "\n";
std::cout << p3 << " > " << p1 << ": " << (p3 > p1) << "\n";
std::cout << p3 << " >= " << p1 << ": " << (p3 >= p1) << "\n";
}

CRTP实现单例。

template
class Singleton {
public:
static T& instance() {
static T instance_;
return instance_;
}

Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;

protected:
Singleton() = default;
~Singleton() = default;
};

class Logger : public Singleton {
friend class Singleton;
int log_count_ = 0;
Logger() = default;

public:
void log(const std::string& msg) {
std::cout << "[LOG " << ++log_count_ << "] " << msg << "\n";
}
};

void singleton_crtp() {
auto& logger = Logger::instance();
logger.log("First message");
logger.log("Second message");

auto& logger2 = Logger::instance();
std::cout << "Same instance: " << (&logger == &logger2) << "\n";
}

CRTP实现克隆。

template
class Cloneable {
public:
std::unique_ptr clone() const {
return std::unique_ptr(
static_cast(this->clone_impl())
);
}

private:
virtual Cloneable* clone_impl() const = 0;
};

class ConcreteCloneable : public Cloneable {
int value_;
public:
explicit ConcreteCloneable(int v) : value_(v) {}

ConcreteCloneable* clone_impl() const override {
return new ConcreteCloneable(value_);
}

int value() const { return value_; }
};

void clone_demo() {
ConcreteCloneable original(42);
auto copy = original.clone();
std::cout << "Cloned value: " << copy->value() << "\n";
}

CRTP在C++中广泛应用,结合了模板的编译期效率和面向对象的表达力。

http://www.jsqmd.com/news/1036305/

相关文章:

  • 2026年连云港装修公司精选指南,打造梦想家园不再难
  • 终极指南:如何为Windows 11 24H2 LTSC一键恢复微软商店完整功能
  • Office Custom UI Editor:打造专属Office界面的终极免费工具
  • dnsmasq搭建简易DNS服务器--dnsmasq_windows版
  • 稳压二极管使用指南
  • 嵌入式GUI开发:emWin中MULTIEDIT与MULTIPAGE控件的深度应用与优化
  • 鲸剪 WhaleClip怎么样?5款图生视频深度对比
  • 2026论文顶级降AI率网站大曝光:智能算法直击安全阈值
  • Gemini多模态原语系统:统一token与解码器架构的技术本质
  • 2026年长沙劳力士、卡地亚手表回收榜单,S级首选敲定禹竞名奢汇 - 名奢变现站
  • 东莞本地企业做GEO靠谱服务商推荐:三家主流GEO服务商横向测评与选型指南 - 子柔传媒
  • 2026 年济宁瓷砖品牌TOP5 榜单:贝索斯瓷砖实力优选测评 - 速递信息
  • 麒麟Kylin系统上PostgreSQL部署与远程访问配置实战
  • MC9RS08KA2软件堆栈与ADC实现:8位MCU资源受限下的嵌入式开发技巧
  • VeRL-DAPO精度问题数值计算分析
  • Windows音频系统的终极解决方案:Equalizer APO实现专业级系统均衡器
  • 2026丽江美食餐厅TOP榜:本地人推荐这3家 - 资讯速览
  • 2026年湖南人力资源外包与技能培训完全指南:从风电运维到AI数字IP的产教融合破局 - 年度推荐企业名录
  • 二手手机靠谱平台有哪些?京东拍拍二手 - 资讯速览
  • 郑州投资金条回收渠道推荐合扬,紧跟大盘价不暗藏扣费 - 开心测评
  • 如何快速获取中兴光猫完全控制权限:3步解锁工厂模式实用指南
  • 海口卖手表选收的顶:本地合规实体店汇总与避坑干货指南 - 奢侈品回收评测
  • 专业级B站视频下载解决方案:BBDown一站式高效下载工具
  • 闲置高端金饰寻新值,同城上门私密交易 - 开心测评
  • 2026广州团建公司排名|合规性价比实测榜单,企业HR优选参考 - 友人团建
  • 125、飞控中的时间管理:系统时钟与定时器
  • 2026西湖区回收虚报成色压价,没对照价目表出爱彼卡地亚亏惨 - 逸程
  • 2026 江门黄金回收行情门店对比 合规透明三家回收渠道参考 - 靖昱黄金回收
  • DeepSeek首发昇腾意味着什么:CUDA生态松动的技术真相
  • 2026上海黄金回收测评:收的顶不压价,无套路!当面检测结款 - 奢侈品回收评测