c++之CRTP

CRTP概述

CRTP,即奇异递归模板模式(Curiously Recurring Template Pattern),由James O. Coplien在其1995年的论文中首次提出,是C++中一个独特而强大的设计模式。它利用模板和继承的特性,允许在编译时进行多态操作,从而提高代码的性能和灵活性。

代码示例

template<typename T>
class base {
public:
    virtual ~base(){}
    void interface(){
        static_cast<T*>(this)->imp();
    }
};

class derived:public base<derived> {
public:
    void imp(){
        cout << " hello world " << endl;
    }
};

多态实现对比

C++ 通过虚函数实现多态,但是虚函数会影响类的内存布局,并且虚函数的调用会增加运行时的开销。具体为:

  1. 每一个虚函数都需要额外得指针寻址
  2. 虚函数表现为多态时不能内敛,如果小函数多得话有比较大得性能损失
  3. 每个对象都需要额外得虚指针指向虚表

在C++编程中,静态多态(Static Polymorphism)是一种使用模板实现的编译时多态。CRTP作为实现静态多态的有效方式,通过模板类和继承机制,使得子类可以在不增加运行时开销的情况下重用和扩展基类的功能,提高性能。

应用

1.将某个类变为单例

template<typename T>
class singlePatternTemplate
{
public:
    virtual ~singlePatternTemplate() {}
    singlePatternTemplate(const singlePatternTemplate&) = delete;
    singlePatternTemplate & operator=(const singlePatternTemplate&) = delete;

    static T& getSingleObj()
{
        static T obj;
        return obj;
    }
protected:
    singlePatternTemplate(){}
};

class derivedDemo :public singlePatternTemplate<derivedDemo>
{
    friend singlePatternTemplate<derivedDemo>;
private:
    derivedDemo(){}
};

2.静态多态


#include <iostream>

// CRTP基类模板

template<typename Derived>

class Shape {

public:

  void draw() {
    static_cast<Derived*>(this)->doDraw();  // 静态转换为派生类并调用doDraw()
  }

};

// 派生类&#x
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值