尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

C++CRTP奇异递归模板

C++CRTP奇异递归模板
📅 发布时间:2026/6/18 14:27:01

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++中广泛应用,结合了模板的编译期效率和面向对象的表达力。

相关新闻

  • 终极指南:如何为Windows 11 24H2 LTSC一键恢复微软商店完整功能
  • 2026年连云港装修公司精选指南,打造梦想家园不再难
  • 嵌入式GUI开发:emWin中MULTIEDIT与MULTIPAGE控件的深度应用与优化

最新新闻

  • UniHacker:跨平台Unity许可证管理技术解决方案
  • 2026年美业培训机构避坑指南:长沙化妆学校、美甲美睫纹绣培训全景对标 - 年度推荐企业名录
  • ViT实战手记:从Patch Embedding到TensorRT部署
  • 2026盘锦大洼区闲置黄金变现全攻略|5家沿街实体店深度对比,高位金价出手怎么选不踩坑 - 行行星
  • 2026年6月核心快讯:杭州帝舵手表保养收费价格与南京法穆兰保养收费明细 - 亨得利官方售后
  • 论文双检时代破局:告别无效改写,百考通AI一站式解决重复率与AIGC超标难题

日新闻

  • 2026年不锈钢卷板厂家推荐排行榜:冷轧热轧/304/201不锈钢卷板,高颜值耐腐蚀源头厂家实力精选 - 企业推荐官【官方】
  • FLUX.1-dev FP8模型实战指南:24GB以下显卡高效部署方案
  • 2026佛山长途搬家价目表:跨省跨市搬家费用完整计算指南 - 从来都是英雄出少年

周新闻

  • 3步解锁iOS设备:applera1n激活锁绕过完全指南
  • 39 2026 人工智能证书终极盘点,普通人选 AI 证书可以从这些方向入手
  • Redis 暴露公网有多危险?从端口检查到补救步骤

月新闻

  • 【总结】入门篇:50句话让你记住架构核心概念
  • WeChatMsg技术方案解析:实现Mac微信数据自主管理的完整解决方案
  • WeChatMsg:革新性微信数据备份方案,打造你的专属数字记忆库

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号