C++:使用 CRTP 模式实现静态多态
大家好,今天介绍 CRTP。最近我在捣鼓 Eigen 线代库,发现里面大量使用了这种模式,所以稍微研究一下。CRTP(Curiously Recurring Template Pattern)是 C++ 中的一种设计模式,特点是利用模板和继承,在基类关联派生类模板参数,来实现静态多态性。
为了更好理解,下面通过一个例子来解释 CRTP 的用法。
经典例子:形状的面积计算 假设要计算不同形状的面积,比如圆形和矩形。通过一个基类来实现公共的接口,同时每个形状能够提供自己的计算逻辑。
定义基类 定义一个模板基类 Shape,它接受一个派生类作为模板参数。
1#include <iostream> 2#include <cmath> 3 4template <typename Derived> 5class Shape { 6public: 7 void area() { 8 static_cast<Derived*>(this)->computeArea(); 9 } 10}; 基类中,area 调用了派生类 computeArea 方法。用 static_cast 可以确保在编译时进行类型检查。
定义派生类 定义两个派生类Circle 和 Rectangle。
1class Circle : public Shape<Circle> { 2public: 3 Circle(double radius) : radius(radius) {} 4 5 void computeArea() { 6 double area = M_PI * radius * radius; 7 std::cout << "Circle area: " << area << std::endl; 8 } 9 10private: 11 double radius; 12}; 13 14class Rectangle : public Shape<Rectangle> { 15public: 16 Rectangle(double width, double height) : width(width), height(height) {} 17 18 void computeArea() { 19 double area = width * height; 20 std::cout << "Rectangle area: " << area << std::endl; 21 } 22 23private: 24 double width, height; 25}; 每个派生类实现 computeArea 方法。
Read more...