簡體   English   中英

如何定義從自定義迭代器到自定義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_hintemplace_hint類的操作應將const_iterator參數作為輸入,但是我需要定義一個從iteratorconst_iterator的隱式轉換,以便按用戶期望的那樣工作。

我很確定將const iterator隱式轉換為const_iterator應該可以,但是我不確定在語法上該怎么做。 對我來說,在模板(或其他機制)上具有某種條件以防止const_iterator轉換為iterator也是很重要的。

如何定義這種轉換?

有兩種編寫隱式轉換的方法。

  1. 為采用iterator const_iterator編寫一個轉換構造iterator
  2. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM