C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > c++ CRTP模式

c++ CRTP模式的使用小结

作者:a353541382

CRTP是C++中一种高级的模板编程技术,它通过将派生类作为基类的模板参数来实现编译期多态,本文就来介绍一下c++ CRTP模式的使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

CRTP(Curiously Recurring Template Pattern,奇异递归模板模式)是C++中一种高级的模板编程技术,它通过将派生类作为基类的模板参数来实现编译期多态。

1. CRTP的基本概念

基本结构

// 基类模板
template<typename Derived>
class Base {
public:
    void interface() {
        // 将调用转发给派生类的实现
        static_cast<Derived*>(this)->implementation();
    }
    
    void static_interface() {
        // 调用派生类的静态方法
        Derived::static_implementation();
    }
};

// 派生类
class Derived : public Base<Derived> {  // 关键:将自己作为模板参数
public:
    void implementation() {
        std::cout << "Derived implementation" << std::endl;
    }
    
    static void static_implementation() {
        std::cout << "Derived static implementation" << std::endl;
    }
};

2. CRTP的核心原理

编译期多态

template<typename Derived>
class Base {
public:
    // 编译期多态:调用哪个implementation在编译时确定
    void foo() {
        static_cast<Derived*>(this)->implementation();
    }
    
    // 可以添加默认实现
    void bar() {
        std::cout << "Base default implementation" << std::endl;
    }
};

3. CRTP的常见应用

应用1:静态多态(编译期多态)

template<typename Derived>
class Shape {
public:
    void draw() const {
        // 编译期调用派生类的具体实现
        static_cast<const Derived*>(this)->draw_impl();
    }
    
    double area() const {
        return static_cast<const Derived*>(this)->area_impl();
    }
};

class Circle : public Shape<Circle> {
private:
    double radius;
    
public:
    Circle(double r) : radius(r) {}
    
    // 实现基类期望的方法
    void draw_impl() const {
        std::cout << "Drawing Circle with radius " << radius << std::endl;
    }
    
    double area_impl() const {
        return 3.14159 * radius * radius;
    }
};

class Square : public Shape<Square> {
private:
    double side;
    
public:
    Square(double s) : side(s) {}
    
    void draw_impl() const {
        std::cout << "Drawing Square with side " << side << std::endl;
    }
    
    double area_impl() const {
        return side * side;
    }
};

// 使用
template<typename T>
void processShape(const Shape<T>& shape) {
    shape.draw();
    std::cout << "Area: " << shape.area() << std::endl;
}

int main() {
    Circle circle(5.0);
    Square square(4.0);
    
    processShape(circle);  // 编译时生成Circle版本
    processShape(square);  // 编译时生成Square版本
}

应用2:计数器模式

// 统计某个类创建的对象数量
template<typename T>
class Counter {
protected:
    Counter() { ++count; }
    Counter(const Counter&) { ++count; }
    Counter(Counter&&) { ++count; }
    ~Counter() { --count; }
    
public:
    static int getCount() { return count; }
    
private:
    static int count;
};

// 静态成员初始化
template<typename T>
int Counter<T>::count = 0;

// 使用
class MyClass1 : public Counter<MyClass1> {
    // ...
};

class MyClass2 : public Counter<MyClass2> {
    // ...
};

int main() {
    MyClass1 a, b, c;
    MyClass2 x, y;
    
    std::cout << "MyClass1 count: " << MyClass1::getCount() << std::endl;  // 3
    std::cout << "MyClass2 count: " << MyClass2::getCount() << std::endl;  // 2
    // 注意:每个Counter实例都有自己的静态count
}

应用3:多态拷贝(虚拟构造函数)

template<typename Derived>
class Cloneable {
public:
    // 虚拟构造函数模式
    Derived* clone() const {
        return new Derived(static_cast<const Derived&>(*this));
    }
    
protected:
    // 防止直接实例化
    Cloneable() = default;
    ~Cloneable() = default;
};

class ConcreteClass : public Cloneable<ConcreteClass> {
public:
    int value;
    
    ConcreteClass(int v) : value(v) {}
    
    // 自动获得clone()方法
    // 可以调用clone()来创建副本
};

int main() {
    ConcreteClass obj1(42);
    ConcreteClass* obj2 = obj1.clone();
    
    std::cout << obj2->value << std::endl;  // 42
    
    delete obj2;
}

应用4:静态接口检查

// 混入模式:为类添加功能
template<typename Derived>
class Comparable {
public:
    bool operator==(const Derived& other) const {
        return !(static_cast<const Derived&>(*this) < other) &&
               !(other < static_cast<const Derived&>(*this));
    }
    
    bool operator!=(const Derived& other) const {
        return !(*this == other);
    }
    
    bool operator<=(const Derived& other) const {
        return !(other < static_cast<const Derived&>(*this));
    }
    
    bool operator>=(const Derived& other) const {
        return !(static_cast<const Derived&>(*this) < other);
    }
    
    bool operator>(const Derived& other) const {
        return other < static_cast<const Derived&>(*this);
    }
};

// 只需要实现operator<,自动获得所有比较操作
class MyInt : public Comparable<MyInt> {
public:
    int value;
    
    MyInt(int v) : value(v) {}
    
    bool operator<(const MyInt& other) const {
        return value < other.value;
    }
};

int main() {
    MyInt a(10), b(20), c(10);
    
    std::cout << std::boolalpha;
    std::cout << (a < b) << std::endl;   // true
    std::cout << (a == b) << std::endl;  // false
    std::cout << (a == c) << std::endl;  // true
    std::cout << (a != b) << std::endl;  // true
    std::cout << (a <= c) << std::endl;  // true
}

4. CRTP的高级用法

访问派生类成员

template<typename Derived>
class AccessDerived {
public:
    void printInfo() {
        Derived* derived = static_cast<Derived*>(this);
        
        // 访问派生类的protected成员
        std::cout << "Value: " << derived->value << std::endl;
        
        // 调用派生类的protected方法
        derived->protectedMethod();
    }
    
protected:
    // 基类可以提供一些默认实现
    virtual void protectedMethod() {
        std::cout << "Base protected method" << std::endl;
    }
};

class MyDerived : public AccessDerived<MyDerived> {
    friend class AccessDerived<MyDerived>;  // 允许基类访问protected成员
    
protected:
    int value = 42;
    
    void protectedMethod() override {
        std::cout << "Derived protected method" << std::endl;
    }
};
多级CRTP
template<typename Derived>
class Level1 {
public:
    void level1Method() {
        std::cout << "Level1 calling: ";
        static_cast<Derived*>(this)->implement();
    }
};

template<typename Derived>
class Level2 : public Level1<Derived> {
public:
    void level2Method() {
        std::cout << "Level2 calling: ";
        static_cast<Derived*>(this)->implement();
    }
};

class FinalClass : public Level2<FinalClass> {
public:
    void implement() {
        std::cout << "FinalClass implementation" << std::endl;
    }
};

CRTP + 策略模式

// 策略接口
template<typename T>
class SerializationStrategy {
public:
    std::string serialize(const T& obj) const {
        return static_cast<const T*>(this)->serializeImpl();
    }
};

// 具体策略
class JSONSerialization : public SerializationStrategy<JSONSerialization> {
public:
    std::string serializeImpl() const {
        return "{ \"type\": \"json\" }";
    }
};

class XMLSerialization : public SerializationStrategy<XMLSerialization> {
public:
    std::string serializeImpl() const {
        return "<type>xml</type>";
    }
};

// 使用策略的类
template<typename SerializationStrategy>
class DataProcessor {
private:
    SerializationStrategy serializer;
    
public:
    std::string process() {
        return serializer.serialize(serializer);
    }
};

6. CRTP的最佳实践

实践1:使用类型检查

template<typename Derived>
class Base {
    // 编译时检查:确保Derived是从Base<Derived>派生的
    static_assert(std::is_base_of<Base<Derived>, Derived>::value,
                  "Derived must inherit from Base<Derived>");
    
    // C++17的更简洁写法
    static_assert(std::is_base_of_v<Base, Derived>);
};

实践2:保护构造函数

template<typename Derived>
class Base {
protected:
    // 防止直接实例化Base
    Base() = default;
    ~Base() = default;
    
    // 防止在堆上创建Base
    void* operator new(std::size_t) = delete;
    void operator delete(void*) = delete;
};

实践3:使用CRTP实现Mixin

// Mixin:为类添加功能
template<template<typename> class... Mixins>
class MixedClass : public Mixins<MixedClass<Mixins...>>... {
    // 继承多个Mixin
};

// 定义Mixin
template<typename Derived>
class Printable {
public:
    void print() const {
        std::cout << "Printing..." << std::endl;
    }
};

template<typename Derived>
class Serializable {
public:
    std::string serialize() const {
        return "Serialized";
    }
};

// 使用
using MyClass = MixedClass<Printable, Serializable>;

7. CRTP在实际项目中的应用

示例:数学向量库

template<typename Derived, typename T>
class VectorExpression {
public:
    size_t size() const {
        return static_cast<const Derived*>(this)->size();
    }
    
    T operator[](size_t i) const {
        return static_cast<const Derived*>(this)->operator[](i);
    }
    
    // 延迟计算:表达式模板
    Derived& operator+=(const VectorExpression& other) {
        Derived& self = *static_cast<Derived*>(this);
        for (size_t i = 0; i < size(); ++i) {
            self[i] += other[i];
        }
        return self;
    }
};

template<typename T>
class Vector : public VectorExpression<Vector<T>, T> {
private:
    std::vector<T> data;
    
public:
    Vector(size_t n, T val = T{}) : data(n, val) {}
    
    size_t size() const { return data.size(); }
    
    T operator[](size_t i) const { return data[i]; }
    T& operator[](size_t i) { return data[i]; }
    
    // 允许从任何VectorExpression构造
    template<typename E>
    Vector(const VectorExpression<E, T>& expr) : data(expr.size()) {
        for (size_t i = 0; i < expr.size(); ++i) {
            data[i] = expr[i];
        }
    }
};

8. CRTP的局限性

9. 何时使用CRTP

适合使用CRTP的情况:

不适合使用CRTP的情况:

总结

CRTP是C++模板元编程中的强大工具,它通过编译期多态提供了零开销的抽象能力。虽然学习曲线较陡,但在性能敏感的场景下,CRTP可以替代虚函数,提供更好的运行时性能。
记住CRTP的核心思想:基类通过static_cast将this指针转换为派生类指针,从而调用派生类的方法,所有这一切都在编译期完成。

到此这篇关于c++ CRTP模式的使用小结的文章就介绍到这了,更多相关c++ CRTP模式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文