在查看c++ stl头文件源码stl_list.h时发现typename的用法。
//stl_list.h中list模板类的源码
template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
class list: protected _List_base<_Tp, _Alloc>
{
//conccept requirements
typedef typename _Alloc::value_type _Alloc_value_type;
......
}
_Alloc是一个模板参数,而_Alloc::value_type中value_type是依赖于_Alloc的类型的。对于value_type等依赖于模板参数的名字叫做“依赖名字”,如果value_type又是嵌套在类中,那么它叫“嵌套依赖名字”。
此时,在_Alloc被明确前,value_type实际是什么都是未知的,它有可能是一个类型,也可能是个静态成员变量。虽然我们在使用的时候知道它是一个类型,但编译器并不知道,所以如果_Alloc::value_type前面不加 typename将会报错。当我们加上typename后,即相当于告诉了编译器,value_type是作为一种类型去使用的。
我们写段demo验证以下
template <typename T>
class Test
{
typedef T::DataType D;
};
int main()
{
return 0;
}
定义一个模板类Test,用typedef重命名T::DataType为 D
用g++编译:g++ -c main.cpp -o main.o
此时编程器报错,提示T::data前需要typename,因为‘T’是一个有依赖的作用域。
当我们加上typename,可正常编译通过
template<typename T>
class Test
{
typedef typename T::DataType D;
};
下方连接对此做了详细介绍:
https://blog.csdn.net/dick_china/article/details/4522253
网友评论