Use Case

Polymorphism in Compile Time

可以实现编译器的多态,也可以实现隐藏子类的具体实现,只暴露接口.

Polymorphism in Compile Time
1
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(); // 编译期确定具体类型
}

代码复用

Mixin
1
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;
}
};
// Point 自动获得 != 运算符