![](/img/trans.png)
[英]Custom container list: problem with compiling from iterator to const_iterator
[英]how to define implicit conversion from custom iterator to custom const_iterator
我正在編寫一個STL樣式的“ Tree”容器類。 我目前使用具有以下慣用法的單個類支持const和非const迭代器:
template<typename T>
class Tree
{
public:
using iterator = TreeIterator<T, false>;
using const_iterator = TreeIterator<T, true>;
// ...
};
而TreeIterator
就像這樣:
template <typename T, bool is_const_iterator/* = true*/>
class TreeIterator : public std::iterator<std::forward_iterator_tag, T>
{
public:
// TreeNodePointer is either a const or non-const pointer depending on the template parameter.
typedef typename std::conditional<is_const_iterator, const TreeNode<T>*, TreeNode<T>*>::type TreeNodePointer;
// All the iterator interface and typedefs...
private:
TreeNodePointer m_pointer; // internal pointer.
};
問題是,要保持我的“ STL樣式”,像insert_hint
或emplace_hint
類的操作應將const_iterator
參數作為輸入,但是我需要定義一個從iterator
到const_iterator
的隱式轉換,以便按用戶期望的那樣工作。
我很確定將const iterator
隱式轉換為const_iterator
應該可以,但是我不確定在語法上該怎么做。 對我來說,在模板(或其他機制)上具有某種條件以防止const_iterator
轉換為iterator
也是很重要的。
如何定義這種轉換?
有兩種編寫隱式轉換的方法。
iterator
const_iterator
編寫一個轉換構造iterator
。 iterator
編寫一個轉換函數,該函數可以轉換為const_iterator
。 在這種情況下,最簡單的方法可能是編寫轉換函數:
operator TreeIterator<T, true>() const { return /* ... */; }
此函數將同時存在於TreeIterator<T, true>
和TreeIterator<T, false>
,但是如果對象已經是TreeIterator<T, true>
,則實際上不會使用該函數。 完全沒有可能進行相反的轉換,因為沒有為此編寫任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.