typename 的特殊使用场景
在模板编程中,typename 和 class 常被用来定义模板参数,但在某些特定场景下,必须显式使用 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::const_iterator it = con.begin();
编译器在处理模板时,遇到 无法确定它到底是一个类型还是一个静态成员变量。如果它是类型,语法合法;如果是变量,则非法。因为 此时是未知的模板参数,编译器无法预知它内部结构。


