對不起,長標題。爲什麼編譯器不能區分typedef和non-typedef?
我有一個類List一個typedef:
template <typename T>
class List {
// Think of a class Iter_ with ListElem *pCurrentPos and List *pList
typedef const Iter_ const_iterator;
const_iterator cbegin() const;
};
和外部類的定義,但在頭文件中。
template <typename T>
typename List<T>::const_iterator List<T>::cbegin() const {}
這將產生錯誤C2373:Redefinition; different type modifiers
我重寫功能,如下所示:
template <typename T>
const typename List<T>::Iter_ List<T>::cbegin() const {}
和誤差消失;該程序編譯正確。 (想想這些事例中我沒有返回任何東西;這與示例無關)
什麼是編譯器解釋錯誤的版本,阻止成功編譯第二個版本沒有,以及我怎樣才能補救這個?
更多的代碼
我使用VS2008
的(富勒)的代碼示例我目前編程:
template <typename T>
class List
{
public:
// Forward declaration.
class Iter_;
private:
/////////////////////////////////////////////////////////
// ListElem
/////////////////////////////////////////////////////////
struct ListElem
{
T data;
// Doubly-linked list.
ListElem *next;
ListElem *prev;
};
class ListException {};
////////////////////////////////////////////////////////
// List Members
////////////////////////////////////////////////////////
// Point to first elem.
ListElem *head_;
// Point to last elem.
ListElem *tail_;
public:
//////////////////////////////////////////////////////////
// Typedefs
//////////////////////////////////////////////////////////
typedef Iter_ iterator;
typedef const Iter_ const_iterator;
//////////////////////////////////////////////////////////
// Iterator class
//////////////////////////////////////////////////////////
class Iter_
{
public:
Iter_(ListElem *pCurr, List *pList)
: pCurr_(pCurr), pList_(pList)
{ }
T& operator*()
{
if(*this == pList_->end())
throw ListException();
else
return pCurr_->data;
}
private:
ListElem *pCurr_;
List *pList_;
};
iterator begin();
iterator end();
const_iterator cbegin() const;
const_iterator cend() const;
};
template <typename T>
List<T>::List()
: head_(0), tail_(0), size_(0)
{ }
template <typename T>
List<T>::~List()
{
//this->clear();
}
template <typename T>
List<T>::List(List const& other)
: size_(other.size_)
{
//this->clone(other);
}
template <typename T>
List<T>& List<T>::operator=(List const& other)
{
size_ = other.size_;
//this->clone(other);
}
// Compiles ok
template <typename T>
typename List<T>::iterator List<T>::begin()
{
if(!head_)
head_ = new ListElem();
return iterator(head_, this);
}
// Compiles ok
template <typename T>
typename List<T>::iterator List<T>::end()
{
return iterator(tail_, this);
}
// Compiler error
template <typename T>
typename List<T>::const_iterator List<T>::cbegin() const
{
return const_iterator(head_, this);
}
// Compiles ok
template <typename T>
typename const List<T>::Iter_ List<T>::cend() const
{
return const_iterator(tail_, this);
}
在哪裏(以及如何)定義了'Iter_'? – atzz 2010-12-17 16:31:04
comeau編譯它就好了(除了'typename const List :: Iter_ etc ...'應該是'const typename etc ...') –
lijie
2010-12-17 16:33:14
@atzz:我已經添加了額外的代碼。 – IAE 2010-12-17 16:33:41