CRTP: Static Polymorphism in C++
Use Case
Polymorphism in Compile Time
可以实现编译器的多态,也可以实现隐藏子类的具体实现,只暴露接口.
Polymorphism in Compile Time1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| template <typename Derived> class Shape { public: void draw() const { static_cast<const Derived*>(this)->draw_impl(); } };
class Circle : public Shape<Circle> { public: void draw_impl() const { } };
class Square : public Shape<Square> { public: void draw_impl() const { } };
template <typename T> void render(const Shape<T>& shape) { shape.draw(); }
|
代码复用
Mixin1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| template <typename Derived> class Comparable { public: bool operator!=(const Derived& other) const { return !(static_cast<const Derived&>(*this) == other); } };
class Point : public Comparable<Point> { int x, y; public: bool operator==(const Point& other) const { return x == other.x && y == other.y; } };
|