为什么我们需要typename这里? [英] Why do we need typename here?
问题描述
template<class T>
class Set
{
public:
void insert(const T& item);
void remove(const T& item);
private:
std::list<T> rep;
}
template<typename T>
void Set<T>::remove(const T& item)
{
typename std::list<T>::iterator it = // question here
std::find(rep.begin(),rep.end(),itme);
if(it!=rep.end()) rep.erase(it);
}
为什么需要remove / p>
Why the typename in the remove() is needed?
推荐答案
一般来说,C ++需要 typename
,因为不幸的语法[ ]它继承自C,这使得不可能没有非本地信息,例如 - 在 A * B;
是否 A
命名一个类型(在这种情况下,这是一个 B
作为指向它的指针的声明)或不是(在这种情况下,这是一个乘法表达式 - - 很可能,因为 A
,对于所有你可以告诉没有非本地信息,可以是重载 operator * $
In general, C++ needs typename
because of the unfortunate syntax [*] it inherits from C, that makes it impossible without non-local information to say -- for example -- in A * B;
whether A
names a type (in which case this is a declaration of B
as a pointer to it) or not (in which case this is a multiplication expression -- quite possible since A
, for all you can tell without non-local information, could be an instance of a class that overloads operator*
to do something weird;-).
在大多数情况下,编译器确实具有消除歧义所需的非本地信息(虽然不幸的语法仍然意味着低级解析器需要来自更高层的反馈,保持符号表信息)...但是使用模板它不(通常不是,虽然在这种特定情况下,专门化 std :: list< T>
,以使其 :: iterator
不是类型名称; - )。
In most cases the compiler does have the non-local information needed to disambiguate (though the unfortunate syntax still means the low-level parser needs feedback from the higher-level layer that keeps the symbol table info)... but with templates it doesn't (not in general, though in this specific case it might be technically illegal to specialize a std::list<T>
so that its ::iterator
is NOT a type name;-).
[*]不仅仅是我的意见,还包括Ken Thompson和Rob Pikes的意见,目前我的同事,他们忙于设计和实现一种新的内部使用的编程语言:新的编程语言,而其语法大多是C样,不重复C的语法设计错误 - 它是新的语言(如eg在好的老Pascal),语法足以区分标识符必须命名一个类型从不必须; - )。
[*] not just my opinion, but also the opinion of Ken Thompson and Rob Pikes, currently my colleagues, who are busy designing and implementing a new programming language for internal use: that new programming language, while its syntax is mostly C-like, does NOT repeat C's syntax design errors -- it the new language (like e.g. in good old Pascal), syntax is sufficient to distinguish identifiers that must name a type from ones that must not;-).
这篇关于为什么我们需要typename这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!