typename在模板中,为什么会减少歧义?

更好的使用模板

代码出处

简单来说,当我们引用依赖于模板参数的名字(dependent name)时,编译器无法提前知道它是类型名还是变量名,所以必须用 typename 来显式告诉编译器它是一个类型。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>

int p = 1;
template<typename T>
void foo(const std::vector<T> &v)
{
std::vector<T>::const_iterator* p;
// 这里 T 是模板参数,所以整个表达式依赖于 T

}
...

如上的情况,因为某个变量(p)声明依赖于模板参数(T),并且没有typename,所以编译器会将const_iterator当作一个变量,然后和p相乘。

解决歧义的方法

加上 typename

1
2
typename std::vector<T>::const_iterator it = v.begin(); //明确告诉编译器,const_iterator是一个类型名

但是,不可单独只加上typedef,这样会导致错误:

1
2
3
4
E:\test\test.cpp:16:13: error: need 'typename' before 'std::vector<T>::const_iterator' because 'std::vector<T>' is a dependent scope [-Wtemplate-body]
16 | typedef std::vector<T>::const_iterator* p;
| ^~~
| typename

使用typedef

1
2
typedef int value_t; // member of current instantiation


typename在模板中,为什么会减少歧义?
https://weihehe.top/2025/10/13/typename在模板中,为什么会减少歧义?/
作者
weihehe
发布于
2025年10月13日
许可协议