20200301
Plan
60min: cpp template
Notes
- shared_ptr 和 unique_ptr 的删除器是在不同阶段进行绑定的,shared_ptr 提供显式的调用 reset,这个时候,reset 是一个模版函数,需要接收一个 delete 模版,因此提供了方便的接口,真正的调用会多一次判断,而 unique_ptr 将删除器作为类的一部分,这个实在编译阶段就绑定好了,稍微高效一点。
- 模版的实例化会在不同的编译单元里面进行,因此为了减少在多个对象文件中的重复实例化对象,可以提供显式实例化的声明和定义(指定好模版参数的实参),遇到 extern 的显式实例化声明,就不会在本编译单元中进行编译了,也就不会产生重复的实例化对象。
- 普通类和模版类的成员都可以拥有模版
- 当使用
::来访问模版参数的内部名字时,有一个问题需要区分清楚,就是这个名字是一个类型,还是一个变量,默认是变量,如果想让编译器将其识别为类型的话,需要使用 typename 作为前缀进行标记。
练习代码:
#include <iostream>
#include <vector>
template <typename T, typename U, typename V> void f1(T, U, V);
template <typename T> inline T f2(int &t);
template <typename T> void f3(T, T);
typedef char Ctype;
template <typename Ctype> Ctype f4(Ctype a);
template <typename C> void loop(C &container) {
for (typename C::const_iterator it = container.cbegin();
it != container.cend(); it++) {
std::cout << *it << ", " << std::endl;
}
}
template class std::vector<int>;
template void loop(std::vector<int> &container);
int main() {
std::vector<int> v = {1, 2, 3};
loop(v);
return 0;
}