Curiously Recurring Template Pattern奇怪的模板递归 --- C++20

2023-10-20 10:50

本文主要是介绍Curiously Recurring Template Pattern奇怪的模板递归 --- C++20,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Curiously Recurring Template Pattern 奇怪的模板递归 — C++20

我们都知道C++有静态多态和动态多态,动态多态通过虚函数表实现,他的缺点就是对效率产生一点点影响

可以用CRTP解决这个问题

我们先举一个动态多态的例子:

#include <iostream>
using namespace std;class Base
{
public:virtual void invoking(){cout << "Base" << endl;}
};class Derived1 final : public Base
{
public:virtual void invoking() override final{cout << "Derived1" << endl;}
};class Derived2 final : public Base
{
public:virtual void invoking() override final{cout << "Derived2" << endl;}
};int main()
{Derived1* derived1 = new Derived1;Derived2* derived2 = new Derived2;derived1->invoking();derived2->invoking();}

会在运行时查找虚函数表,影响运行时效率

使用CRTP编译器多态

特点:子类继承基类,且基类有一个模板参数,并以子类类型为参数

#include <iostream>
using namespace std;template <typename Derived>
class Base
{
public:void interface(){static_cast<Derived*>(this)->implementation();}void implementation(){cout << "Implementation Base" << endl;}
};class Derived1 :public  Base<Derived1>
{
public:void implementation(){cout << "Implementation Derived1" << endl;}
};class Derived2 : public  Base<Derived2>
{
public:void implementation(){cout << "Implementation Derived2" << endl;}
};class Derived3 : public Base<Derived3>
{
public:
};template <typename T>
void execute(T& base)
{base.interface();
}int main(int argc, char* argv[])
{Derived1 d1;execute(d1);Derived2 d2;execute(d2);Derived3 d3;execute(d3);
}

每个基类都调用 base.interface(); 然后调用static_cast<Derived*>(this)->implementation();

这样就在编译器实现了多态,避免了动态多态

1>class Base<class Derived1>	size(1):
1>	+---
1>	+---
1>class Base<class Derived2>	size(1):
1>	+---
1>	+---
1>class Base<class Derived3>	size(1):
1>	+---
1>	+---

image-20220609223403879

#include <chrono>
#include <iostream>auto start = std::chrono::steady_clock::now();void writeElapsedTime() {auto now = std::chrono::steady_clock::now();std::chrono::duration<double> diff = now - start;std::cerr << diff.count() << " sec. elapsed: ";
}template <typename ConcreteMessage>                        // (1)
struct MessageSeverity {void writeMessage() {                                     // (2)static_cast<ConcreteMessage*>(this)->writeMessageImplementation();}void writeMessageImplementation() const {std::cerr << "unexpected" << std::endl;}
};struct MessageInformation : MessageSeverity<MessageInformation> {void writeMessageImplementation() const {               // (3)std::cerr << "information" << std::endl;}
};struct MessageWarning : MessageSeverity<MessageWarning> {void writeMessageImplementation() const {               // (4)std::cerr << "warning" << std::endl;}
};struct MessageFatal : MessageSeverity<MessageFatal> {};     // (5)template <typename T>
void writeMessage(T& messServer) {writeElapsedTime();messServer.writeMessage();                            // (6)}int main() {std::cout << std::endl;MessageInformation messInfo;writeMessage(messInfo);MessageWarning messWarn;writeMessage(messWarn);MessageFatal messFatal;writeMessage(messFatal);std::cout << std::endl;}

Info;
writeMessage(messInfo);

MessageWarning messWarn;
writeMessage(messWarn);MessageFatal messFatal;
writeMessage(messFatal);std::cout << std::endl;

}


![image-20220609224336869](https://img-blog.csdnimg.cn/img_convert/4ed12bcf5b8ae5ceeaa9a1575e87989a.png)

这篇关于Curiously Recurring Template Pattern奇怪的模板递归 --- C++20的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/246623

相关文章

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么

SpringBoot集成EasyPoi实现Excel模板导出成PDF文件

《SpringBoot集成EasyPoi实现Excel模板导出成PDF文件》在日常工作中,我们经常需要将数据导出成Excel表格或PDF文件,本文将介绍如何在SpringBoot项目中集成EasyPo... 目录前言摘要简介源代码解析应用场景案例优缺点分析类代码方法介绍测试用例小结前言在日常工作中,我们经

C++中全局变量和局部变量的区别

《C++中全局变量和局部变量的区别》本文主要介绍了C++中全局变量和局部变量的区别,全局变量和局部变量在作用域和生命周期上有显著的区别,下面就来介绍一下,感兴趣的可以了解一下... 目录一、全局变量定义生命周期存储位置代码示例输出二、局部变量定义生命周期存储位置代码示例输出三、全局变量和局部变量的区别作用域

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

C++中NULL与nullptr的区别小结

《C++中NULL与nullptr的区别小结》本文介绍了C++编程中NULL与nullptr的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编... 目录C++98空值——NULLC++11空值——nullptr区别对比示例 C++98空值——NUL

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window