Curiously recurring template pattern ( 奇怪的重复模板模式,CRTP)

本文主要是介绍Curiously recurring template pattern ( 奇怪的重复模板模式,CRTP),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

CRTPC++中的一种技术,其中Derived类从类模板Base派生。关键是Base有一个Derived作为模板参数。

template<class T>
class Base{
...
};class Derived : public Base<Derived>{
...
};

CRTP是仅在需要时才实例化类模板的方法,使用静态多态方式。

静态多态与动态多态非常相似。但是与使用虚拟方法的动态多态性相反,方法调用的调度将在编译时进行。

// crtp.cpp#include <iostream>template <typename Derived> 
struct Base{//  void interface(){ implementation(); }//  virtual void implementation(){}void interface(){static_cast<Derived*>(this)->implementation();}void implementation(){std::cout << "Implementation Base" << std::endl;}};struct Derived1: Base<Derived1>{void implementation(){std::cout << "Implementation Derived1" << std::endl;}
};struct Derived2: Base<Derived2>{void implementation(){std::cout << "Implementation Derived2" << std::endl;}
};struct Derived3: Base<Derived3>{};template <typename T>
void execute(T& base){base.interface();
}int main(){std::cout << std::endl;Derived1 d1;execute(d1);Derived2 d2;execute(d2);Derived3 d3;execute(d3);std::cout << std::endl;}

我在函数模板中使用execute(第34-37行)静态多态性。我在每个参数基础上调用方法base.interface

第10-12行中的方法Base :: interface是CRTP习惯用法的关键点。这些方法分派给派生类的实现:static_cast <Derived *>(this)-> implementation()。这是可能的,因为该方法将在调用时实例化。

此时,派生类Derived1,Derived2Derived3已完全定义。因此,方法Base::interface可以使用其派生类的详细信息。特别有趣的是Base :: implementation方法(第14-16行)。该方法充当Derived3类的静态多态性的默认实现(第32行)。

该技术实现了与virtual function的使用相似的效果。如果基类成员函数对所有成员函数调用均使用CRTP,则将在编译时选择派生类中的重写函数。这有效地在编译时模拟了虚拟函数调用系统,而没有大小或函数调用开销(VTBL结构和方法查找,多继承VTBL机制)的开销,但缺点是无法在运行时做出选择。

因此有些人将CRTP的这种特殊用法称为“模拟动态绑定”。 Windows ATL和WTL库中广泛使用此模式。


Mixins with CRTP

Mixins是在类中设计以混合新代码的流行概念。因此,它是Python中通过使用多个继承来更改类的行为的常用技术。与C ++相反,在Python中,在类层次结构中具有一个方法的多个定义是合法的。 Python仅使用方法解析顺序( Method Resolution Order,即MRO)中首先使用的方法。

您可以使用CRTP在C ++中实现mixin。一个著名的例子是类std :: enable_shared_from_this。通过使用此类,您可以创建向自己返回std :: shared_ptr的对象。

您可以从std :: enable_shared_from_this派生您的公共类MySharedClass。现在,您的类MySharedClass具有shared_from_this方法,用于为其对象创建std :: shared_ptr。

#include <iostream>
#include <memory>class ShareMe : public std::enable_shared_from_this<ShareMe> {
public:std::shared_ptr<ShareMe> getShared() {return shared_from_this();}
};int main() {std::shared_ptr<ShareMe> shareMe(new ShareMe);std::shared_ptr<ShareMe> shareMe1 = shareMe->getShared();//std :: shared_ptr <T> :: use_count返回不同shared_ptr实例的数量{auto shareMe2(shareMe1);std::cout << "shareMe.use_count(): " << shareMe.use_count() << std::endl; }std::cout << "shareMe.use_count(): " << shareMe.use_count() << std::endl;//当智能指针中有值的时候,调用reset()会使引用计数减1.shareMe1.reset();std::cout << "shareMe.use_count(): " << shareMe.use_count() << std::endl;return 0;
}

智能指针shareMe(第12行)并复制shareMe1(第13行)和shareMe2(第17行)引用相同的资源,并递增和递减引用计数器。
在这里插入图片描述
mixin的另一个典型用例是您要扩展的类,其类具有其实例支持相等性和不平等性比较的功能。

#include <iostream>
#include <string>template<class Derived>
class Equality 
{};class Apple :public Equality<Apple> {
public:Apple(int s) : size{ s } {};int size;
};class Man :public Equality<Man> {
public:Man(std::string n) : name{ n } {}std::string name;
};template <class Derived>
bool operator == ( Equality<Derived> const & op1 , Equality<Derived> const & op2 ) 
{Derived const& d1 = static_cast<Derived const&>(op1);Derived const& d2 = static_cast<Derived const&>(op2);return !(d1 < d2) && !(d2 < d1);
}template <class Derived>
bool operator != ( Equality<Derived> const & op1 , Equality<Derived> const & op2 )
{Derived const& d1 = static_cast<Derived const&>(op1);Derived const& d2 = static_cast<Derived const&>(op2);return !(op1 == op2);
}bool operator < (Apple const& a1, Apple const& a2) 
{return a1.size < a2.size;
}bool operator < (Man const& m1, Man const& m2)
{return m1.name < m2.name;
}int main() 
{std::cout << std::boolalpha ;Apple apple1{ 5 };Apple apple2{ 10 };std::cout << "apple1 == apple2: " << (apple1 == apple2) << std::endl;Man man1{ "grimm" };Man man2{ "jaud" };std::cout << "man1 != man2: " << (man1 != man2) << std::endl;return 0;
}

参考文章:

  • https://www.modernescpp.com/index.php/specialities-of-std-shared-ptr
  • https://www.modernescpp.com/index.php/c-is-still-lazy

这篇关于Curiously recurring template pattern ( 奇怪的重复模板模式,CRTP)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

poj3468(线段树成段更新模板题)

题意:包括两个操作:1、将[a.b]上的数字加上v;2、查询区间[a,b]上的和 下面的介绍是下解题思路: 首先介绍  lazy-tag思想:用一个变量记录每一个线段树节点的变化值,当这部分线段的一致性被破坏我们就将这个变化值传递给子区间,大大增加了线段树的效率。 比如现在需要对[a,b]区间值进行加c操作,那么就从根节点[1,n]开始调用update函数进行操作,如果刚好执行到一个子节点,

C++11第三弹:lambda表达式 | 新的类功能 | 模板的可变参数

🌈个人主页: 南桥几晴秋 🌈C++专栏: 南桥谈C++ 🌈C语言专栏: C语言学习系列 🌈Linux学习专栏: 南桥谈Linux 🌈数据结构学习专栏: 数据结构杂谈 🌈数据库学习专栏: 南桥谈MySQL 🌈Qt学习专栏: 南桥谈Qt 🌈菜鸡代码练习: 练习随想记录 🌈git学习: 南桥谈Git 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈�

poj2406(连续重复子串)

题意:判断串s是不是str^n,求str的最大长度。 解题思路:kmp可解,后缀数组的倍增算法超时。next[i]表示在第i位匹配失败后,自动跳转到next[i],所以1到next[n]这个串 等于 n-next[n]+1到n这个串。 代码如下; #include<iostream>#include<algorithm>#include<stdio.h>#include<math.

poj3261(可重复k次的最长子串)

题意:可重复k次的最长子串 解题思路:求所有区间[x,x+k-1]中的最小值的最大值。求sa时间复杂度Nlog(N),求最值时间复杂度N*N,但实际复杂度很低。题目数据也比较水,不然估计过不了。 代码入下: #include<iostream>#include<algorithm>#include<stdio.h>#include<math.h>#include<cstring

在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern) 确保一个类只有一个实例,并提供一个全局访问点。 示例代码: class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;this.data = [];}addData(value)

poj 1258 Agri-Net(最小生成树模板代码)

感觉用这题来当模板更适合。 题意就是给你邻接矩阵求最小生成树啦。~ prim代码:效率很高。172k...0ms。 #include<stdio.h>#include<algorithm>using namespace std;const int MaxN = 101;const int INF = 0x3f3f3f3f;int g[MaxN][MaxN];int n

uva 1342 欧拉定理(计算几何模板)

题意: 给几个点,把这几个点用直线连起来,求这些直线把平面分成了几个。 解析: 欧拉定理: 顶点数 + 面数 - 边数= 2。 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#inc

uva 11178 计算集合模板题

题意: 求三角形行三个角三等分点射线交出的内三角形坐标。 代码: #include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#include <stack>#include <vector>#include <

poj 2104 and hdu 2665 划分树模板入门题

题意: 给一个数组n(1e5)个数,给一个范围(fr, to, k),求这个范围中第k大的数。 解析: 划分树入门。 bing神的模板。 坑爹的地方是把-l 看成了-1........ 一直re。 代码: poj 2104: #include <iostream>#include <cstdio>#include <cstdlib>#include <al

最大流、 最小费用最大流终极版模板

最大流  const int inf = 1000000000 ;const int maxn = 20000 , maxm = 500000 ;struct Edge{int v , f ,next ;Edge(){}Edge(int _v , int _f , int _next):v(_v) ,f(_f),next(_next){}};int sourse , mee