项目场景:
为了方便测试,写了一个通用的迭代器打印模板,如下:
template<class Con>
void PrintContainer(const Con& x)
{
Con::const_iterator it = x.begin();
while (it != x.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}
问题描述
本来觉得没什么问题,可是运行之后却报出了如下的错误:
原因分析:
首先,错误信息说const_iterator这个类型是一个从属名称,而类型从属名称要以typename为前缀。那什么是从属名称呢?
从属名称: template内出现的名称,如果依赖于template中的参数,那么它就是一个从属名称。而如果它同时又嵌套与模板参数中,那么它就是一个嵌套从属名称。
拿本题举例,const_iterator是模板中出现的名称,同时又依赖于模板参数Con,同时const_iterator又嵌套与模板参数中,所以const_iterator就是一个嵌套从属名称。
而非从属名称就是不依赖于任何模板参数的。
嵌套的从属名称可能会带来一些问题:
template<typename Con>
void PrintContainer(const Con& c)
{
Con::const_iterator* x;
}
对于上述代码,如果const_iterator是类,则x是一个指向const_iterator的指针,但如果const_iterator是一个变量的名称,则是一个相乘动作。
所以在C++中有一个解析规则:如果解析器在template中遇到一个嵌套的从属名称,那么便假设这个名称不是一个类型,除非通过增加关键字typename来告诉它是一个类型。
解决方案:
我们可以通过增加typename关键字,告诉C++解析器,const_iterator是一个类型。
template<class Con>
void PrintContainer(const Con& x)
{
typename Con::const_iterator it = x.begin();
while (it != x.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}