C++ 模板的两大特性
在 C++ 模板编程里,有两个坑是新手最容易踩到的。一个是 typename 关键字的特殊用法,另一个就是模板定义放在 .cpp 文件导致的链接错误。咱们今天就把这两个问题彻底讲清楚。
typename 的使用场景
刚开始学模板时,我们知道 class 或 typename 用来定义模板参数。但在某些特定场景下,必须显式使用 typename,比如写一个通用的容器打印函数。
#include <iostream>
#include <vector>
#include <list>
using namespace std;
template<class Container>
void Print(const Container& con) {
Container::const_iterator it = con.begin();
while (it != con.end()) {
cout << *it << " ";
it++;
}
cout << endl;
}
int main() {
vector<int> v = {1, 2, 3, 4, 5, 6};
list<int> lt = {1, 2, 3, 4, 5, 6};
Print(v);
Print(lt);
return 0;
}
这段代码试图遍历任意容器。运行时会发现编译报错,问题出在 Container::const_iterator it = con.begin(); 这一行。


