C++:重载常量迭代器的list.end()和list.begin()方法

Chr*_*ris 4 c++ iterator overloading linked-list c++builder

我仍在尝试实现我自己的LinkedList类版本,现在我遇到了为常量迭代器重载方法的问题.例如,当我尝试使用以下代码打印出列表时:

cout << "citer:" << endl;
for (UberList<int>::CIter it = ulist.begin(); it != ulist.end(); ++it)
{
 cout << *it << " ";
}
cout << endl;
Run Code Online (Sandbox Code Playgroud)

我有这些错误:

Error E2034 UberList2.cpp 532: Cannot convert 'UberList<int>::Iter' to 'UberList<int>::CIter' in function main()
Error E2094 UberList2.cpp 532: 'operator!=' not implemented in type 'UberList<int>::CIter' for arguments of type 'UberList<int>::Iter' in function main()
Run Code Online (Sandbox Code Playgroud)

所以据我所知,这意味着使用那些通常的end和begin迭代器方法.以下是我的类中声明这些方法的方法:

Iter begin();
Iter end();
CIter begin() const;
CIter end() const;
Run Code Online (Sandbox Code Playgroud)

template<class T>
typename UberList<T>::Iter UberList<T>::begin()
{
    Iter it;
    it.curr = head;
    return it;
}

template<class T>
typename UberList<T>::Iter UberList<T>::end()
{
 Iter it;
 it.curr = tail->next;
 return it;
}

template<class T>
typename UberList<T>::CIter UberList<T>::begin() const
{
 CIter it;
 it.ccurr = head;
 return it;
}

template<class T>
typename UberList<T>::CIter UberList<T>::end() const
{
 CIter it;
 it.ccurr = tail->next;
 return it;
}
Run Code Online (Sandbox Code Playgroud)

有什么办法可以强制我的程序将这些const方法用于常量迭代器而不是通常的迭代器?我很高兴听到任何建议.

哦,这是我的类的代码在一个文件中以防万一:http://pastebin.com/Jbvv5Hht

Ste*_*sop 7

您应该提供一个转换IterCIter.标准容器(表65,在23.1"容器要求",表示X::iterator可转换为X::const_iterator)

调用者可以const通过使用const引用来确保调用重载,但是你不应该强迫他们这样做,因为他们必须写下这样的东西:

UberList<int>::CIter it = static_cast<const UberList<int> &>(ulist).begin()
Run Code Online (Sandbox Code Playgroud)

如果您提供"必需"转换,则您的调用者无需执行任何特殊操作:您的原始代码将起作用,就像对标准容器一样.