在上一篇文章中
C++:继承、模板、CRTP:谈谈C++多态设计模式_hongwen_yul的博客-CSDN博客
- 我们介绍了C++中关于:继承和模板语法和使用场景,而且我们也提到了,不管是继承还是模板都会有各自弊端:
- 继承由于引入了虚函数(实现动态多态),在子类调用虚函数时,会查表,造成性能损耗。
- 模板虽然可以生成很多遍,但是一旦和模板里面的内容不一样,就需要重新特化,就是说你的所有东西需要重新写一遍。
- 所以为了解决这两个弊端,C++设计出:让继承和模板结合,就恰到好处了,这便是CRTP设计模式 (这便是静态多态概念的提出)
// The Curiously Recurring Template Pattern (CRTP)
template <class T>
class Base
{
// 可以通过类型 T 来使用子类的方法
public:
double get_area(){
return static_cast<T*>(this)->get_area_impl();
}
};
class Derived : public Base<Derived>
{
// 子类具体面积实现
public:
double get_area_impl(){
// .......
}
};
// 统一接口
template<typename T>
double get_area(Base<T> *derived){
return derived->get_area();
}
具体代码就是这样的
#include <iostream>
// 基类
template <typename T>
class Shape
{
private:
// 继承自 T 就可以访问 T 中函数了.
struct accessor : public T
{
double __get_area()
{
return this->T::get_area_impl();
}
};
public:
double get_area()
{
return static_cast<accessor &>(*this).__get_area();
}
};
// 实现 Circle 类
class Circle : public Shape<Circle>
{
private:
double radius = 1;
protected:
double get_area_impl()
{
return 3.1415926 * radius * radius;
}
};
// 实现 Rectangle 类
class Rectangle : public Shape<Rectangle>
{
private:
double a = 1, b = 2;
protected:
double get_area_impl()
{
return a * b;
}
};
// 统一的接口
template <typename Sp>
double get_area(Shape<Sp> *sp)
{
return sp->get_area();
}
int main()
{
Shape<Circle> *c = new Circle;
Shape<Rectangle> *r = new Rectangle;
std::cout << get_area(c) << " " << get_area(r);
return 0;
}
// 打印结果
3.14159 2