这是从斯特劳斯特鲁普常见问题复制的。我见过当您不知道类型时使用了typename,例如在模板template <typename> class some_class
中。为什么在下面的示例中使用typename?
template<class T> void printall(const vector<T>& v)
{
for (auto p = v.begin(); p!=v.end(); ++p)
cout << *p << "\n";
}
In C++98, we'd have to write
template<class T> void printall(const vector<T>& v)
{
for (typename vector<T>::const_iterator p = v.begin(); p!=v.end(); ++p)
cout << *p << "\n";
}
发布于 2012-02-27 19:10:15
你的例子就是典型的例子。由于vector<T>
与模板化参数T
一起使用,所以我们必须告诉编译器::const_iterator
是一种类型。这是为了帮助编译器知道,对于任何T,vector<T>
类型都有一个名为const_iterator的类型。
https://stackoverflow.com/questions/9470718
复制相似问题