得之我幸 失之我命

when someone abandons you,it is him that gets loss because he lost someone who truly loves him but you just lost one who doesn’t love you.

CRTP 简介

CRTP(Curiously Recurring Template Pattern)是 c++ 使用范型实现静态多态的方法,这种方法和虚拟函数比起来优点就是可以节省内存,不需要额外的空间存储 virtual table,并且提高运行速度,运行时不需要动态查找对应的函数

以动物为例实现一个 CRTP,首先基类是一个模板类,模板的参数就是用来告诉基类其运行的子类是什么,以便在编译时静态绑定对应的函数;定义子类时,继承模板类即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

template<typename T>
class Animal
{
public:
void bark() const
{
static_cast<const T*>(this)->bark();
}
};

class Dog: public Animal<Dog>
{
public:
void bark() const
{
cout << "Wang" << endl;
}
};
class Cat: public Animal<Cat>
{
public:
void bark() const
{
cout << "Meow" << endl;
}
};

be slow to promise and quick to perform.