对不起,长标题。为什么编译器不能区分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