奇异递归模板模式(Curiously Recurring Template Pattern)

2024-09-04 05:28

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

奇异递归模板模式(Curiously Recurring Template Pattern) - 知乎 (zhihu.com)

本文来自上面的文章!!!本菜鸡学习和记录一下。

CRTP是C++模板编程时的一种惯用法:把派生类作为基类的模板参数。

1.静态多态

#include <iostream>
using namespace std;template <typename Child>
struct Base
{void interface(){static_cast<Child*>(this)->implementation();}
};struct Derived : Base<Derived>
{void implementation(){cerr << "Derived implementation\n";}
};struct test : Base<test>
{void implementation(){cerr << "test\n";}
};int main()
{Derived d;d.interface();  // Prints "Derived implementation"test t;t.interface();return 0;
}

基类为Base,是模板类,子类Drived继承自Base同时模板参数为Drived,基类中有接口

interface而子类中有接口对应实现implementation,基类interface中将this通过static_cast转换为模板参数类型,这里是Drived,并调用该类型的implemention方法。

为什么是static_cast,而不是dynamic_cast?

因为只有继承了Base的类型才能调用interface且这里是向下转型,所以采用static_cast是安全的。

(不太理解)

通过CRTP可以使得类具有类似于虚函数的效果,同时没有虚函数调用时的开销(虚函数调用时需要通过虚函数指针查找虚函数表进行调用),同时类的对象的体积相比使用虚函数也会减少(不需要存储虚函数指针),但是缺点是无法动态绑定。

2.

template<typename Child>
class Animal
{
public:void Run(){static_cast<Child*>(this)->Run();}
};class Dog :public Animal<Dog>
{
public:void Run(){cout << "Dog Run" << endl;}
};class Cat :public Animal<Cat>
{
public:void Run(){cout << "Cat Run" << endl;}
};template<typename T>
void Action(Animal<T> &animal)
{animal.Run();
}int main()
{Dog dog;Action(dog);Cat cat;Action(cat);return 0;
}

Dog继承自Animal且模板参数为Dog,Cat继承自Animal且模板参数为Cat

Animal,Dog,Cat中都声明了Run,Animal中的Run是通过类型转换后调用模板类型的Run方法实现的。在Action模板参数中接收Animal类型的引用(或指针)并在其中调用了animal对象的Run方法,由于这里传入的是不同的子类对象,因此Action中的animal也会有不同的行为。

3.添加方法,减少冗余

//Vec3
struct Vector3
{float x;float y;float z;Vector3() = default;Vector3(float _x, float _y, float _z);inline Vector3& operator+=(const Vector3& rhs);inline Vector3& operator-=(const Vector3& rhs);//....
};inline Vector3 operator+(const Vector3& lhs, const Vector3& rhs);
inline Vector3 operator-(const Vector3& lhs, const Vector3& rhs);
//....//Vec2
struct Vector2
{float x;float y;Vector2() = default;Vector2(float _x, float _y);inline Vector2& operator+=(const Vector2& rhs);inline Vector2& operator-=(const Vector2& rhs);//....
};inline Vector2 operator+(const Vector2& lhs, const Vector2& rhs);
inline Vector2 operator-(const Vector2& lhs, const Vector2& rhs);
//....

 类型Vector3需要实现+=,-=,+,-等运算符重载。

 类型Vector2需要实现+=,-=,+,-等运算符重载。

其中+=,-=这两个运算符可以采取+,-运算符实现,这时候可以把+=,-=给抽象出来,减少代码冗余。

template<typename T>
struct VectorBase
{T& underlying() { return static_cast<T&>(*this); }T const& underlying() const { return static_cast<T const&>(*this); }inline T& operator+=(const T& rhs) { this->underlying() = this->underlying() + rhs;return this->underlying();}inline T& operator-=(const T& rhs){this->underlying() = this->underlying() - rhs;return this->underlying();}//.....
};struct Vector3 : public VectorBase<Vector3>
{float x;float y;float z;Vector3() = default;Vector3(float _x, float _y, float _z){x = _x;y = _y;z = _z;}
};inline Vector3 operator+(const Vector3& lhs, const Vector3& rhs)
{Vector3 result;result.x = lhs.x + rhs.x;result.y = lhs.y + rhs.y;result.z = lhs.z + rhs.z;return result;
}inline Vector3 operator-(const Vector3& lhs, const Vector3& rhs)
{Vector3 result;result.x = lhs.x - rhs.x;result.y = lhs.y - rhs.y;result.z = lhs.z - rhs.z;return result;
}
//......int main()
{Vector3 v0(6.0f, 5.0f, 4.0f);Vector3 v2(4.0f, 5.0f, 6.0f);v0 += v2;v0 -= v2;return 0;
}

在VectorBase中实现了+=,-=

它们依赖子类的+和-运算符的实现。

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



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

相关文章

SpringBoot如何通过Map实现策略模式

《SpringBoot如何通过Map实现策略模式》策略模式是一种行为设计模式,它允许在运行时选择算法的行为,在Spring框架中,我们可以利用@Resource注解和Map集合来优雅地实现策略模式,这... 目录前言底层机制解析Spring的集合类型自动装配@Resource注解的行为实现原理使用直接使用M

C++中函数模板与类模板的简单使用及区别介绍

《C++中函数模板与类模板的简单使用及区别介绍》这篇文章介绍了C++中的模板机制,包括函数模板和类模板的概念、语法和实际应用,函数模板通过类型参数实现泛型操作,而类模板允许创建可处理多种数据类型的类,... 目录一、函数模板定义语法真实示例二、类模板三、关键区别四、注意事项 ‌在C++中,模板是实现泛型编程

Jackson库进行JSON 序列化时遇到了无限递归(Infinite Recursion)的问题及解决方案

《Jackson库进行JSON序列化时遇到了无限递归(InfiniteRecursion)的问题及解决方案》使用Jackson库进行JSON序列化时遇到了无限递归(InfiniteRecursi... 目录解决方案‌1. 使用 @jsonIgnore 忽略一个方向的引用2. 使用 @JsonManagedR

C#原型模式之如何通过克隆对象来优化创建过程

《C#原型模式之如何通过克隆对象来优化创建过程》原型模式是一种创建型设计模式,通过克隆现有对象来创建新对象,避免重复的创建成本和复杂的初始化过程,它适用于对象创建过程复杂、需要大量相似对象或避免重复初... 目录什么是原型模式?原型模式的工作原理C#中如何实现原型模式?1. 定义原型接口2. 实现原型接口3

大数据spark3.5安装部署之local模式详解

《大数据spark3.5安装部署之local模式详解》本文介绍了如何在本地模式下安装和配置Spark,并展示了如何使用SparkShell进行基本的数据处理操作,同时,还介绍了如何通过Spark-su... 目录下载上传解压配置jdk解压配置环境变量启动查看交互操作命令行提交应用spark,一个数据处理框架

Rust中的BoxT之堆上的数据与递归类型详解

《Rust中的BoxT之堆上的数据与递归类型详解》本文介绍了Rust中的BoxT类型,包括其在堆与栈之间的内存分配,性能优势,以及如何利用BoxT来实现递归类型和处理大小未知类型,通过BoxT,Rus... 目录1. Box<T> 的基础知识1.1 堆与栈的分工1.2 性能优势2.1 递归类型的问题2.2

解决jupyterLab打开后出现Config option `template_path`not recognized by `ExporterCollapsibleHeadings`问题

《解决jupyterLab打开后出现Configoption`template_path`notrecognizedby`ExporterCollapsibleHeadings`问题》在Ju... 目录jupyterLab打开后出现“templandroidate_path”相关问题这是 tensorflo

Java实现状态模式的示例代码

《Java实现状态模式的示例代码》状态模式是一种行为型设计模式,允许对象根据其内部状态改变行为,本文主要介绍了Java实现状态模式的示例代码,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来... 目录一、简介1、定义2、状态模式的结构二、Java实现案例1、电灯开关状态案例2、番茄工作法状态案例

解读静态资源访问static-locations和static-path-pattern

《解读静态资源访问static-locations和static-path-pattern》本文主要介绍了SpringBoot中静态资源的配置和访问方式,包括静态资源的默认前缀、默认地址、目录结构、访... 目录静态资源访问static-locations和static-path-pattern静态资源配置

基于Java实现模板填充Word

《基于Java实现模板填充Word》这篇文章主要为大家详细介绍了如何用Java实现按产品经理提供的Word模板填充数据,并以word或pdf形式导出,有需要的小伙伴可以参考一下... Java实现按模板填充wor编程d本文讲解的需求是:我们需要把数据库中的某些数据按照 产品经理提供的 word模板,把数据