g ++编译器给出了错误:expect`;'在'它'之前
template <typename T>
class myList : public std::list<T>
{
public:
void foo ()
{
std::list<T>::iterator it; // compiler error as above mentioned, why ???
}
};
感谢。
答案 0 :(得分:14)
用g ++。无论何时在模板中,您都会看到错误:
error: expected ';' before 'it'
怀疑你需要一个姓名:
typename std::list<T>::iterator it;
当在模板中声明了一个新类型(在本例中为列表迭代器)时,需要这取决于一个或多个模板参数。这种需求并不是g ++ BTW独有的,它是标准C ++的一部分。
答案 1 :(得分:10)
尼尔给了你答案。也就是说,你可能想要制作一些typedef并使用它们,所以你的工作不会变得那么乏味(它增加了可读性):
template <typename T>
class myList : public std::list<T>
{
public:
typedef T value_type;
typedef const T const_value_type;
typedef value_type& reference;
typedef const_value_type& const_reference;
typedef value_type* pointer;
typedef const_value_type* const_pointer;
typedef std::list<T> base_container;
typedef typename base_container::iterator iterator;
typedef typename base_container::const_iterator const_iterator;
void foo ()
{
iterator it; // easy peasy
}
};
使用typedef是很自由的。
另外,从标准容器继承可能是一个坏主意,因为它们并不是真的用于这样的事情。例如,如果您正在寻找容器的某些扩展,则自由函数通常是best choice。