C++ 模板的两大核心特性
在 C++ 模板编程中,我们常遇到两个棘手的问题:一是 typename 关键字的特殊使用场景,二是模板分离编译导致的链接错误。理解这两个机制,对于编写健壮的泛型代码至关重要。
1. 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;
}
这段代码试图遍历任意容器并打印元素。STL 中的迭代器通常通过 Container::iterator 这种形式访问。然而,直接运行上述代码会报错。问题出在 这一行。


