Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

c++ - 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);

}   

Why the typename in the remove() is needed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;-).

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;-).

[*] 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;-).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...