使用boost :: iterator_facade<&gt ;?为迭代器返回ref,但为const_iterator返回const_ref

时间:2012-09-19 05:51:14

标签: c++ templates boost boost-iterators iterator-facade

我有一个这样的课程,

template <typename Node>
class BSTIteratorBase : public boost::iterator_facade<
    BSTIteratorBase<Node>,
    typename Node::value_type,
    boost::forward_traversal_tag
>
{ ...
    value_type& dereference() const
    { return const_cast<value_type&>( nodePtr_->value_ ); } // Ouch! const_iterator may modify
... };

value_type不依赖于BSTNode类的 constness 。这就是我必须保留const_cast<value_type&>()部分的原因。如何确保const_iterator返回const_refiterator返回可修改的ref?以下是相关的typedef,

template <typename T>
class BinarySearchTree
{
public:
    typedef T                                   value_type;
    typedef T&                                  reference;
    typedef const T&                            const_reference;
    typedef BSTNode<T>                          node_type;    
    typedef BSTNode<T>&                         node_reference;
    typedef BSTNode<T>*                         node_pointer;
    typedef BSTIteratorBase<BSTNode<T>>         iterator;
    typedef BSTIteratorBase<const BSTNode<T>>   const_iterator;

节点类

template <typename T>
class BSTNode
{
public:
    typedef T           value_type;
    typedef T&          reference;
    typedef const T&    const_reference;
    typedef BSTNode     node_type;
    typedef BSTNode*    node_pointer;

    // ctors, dtor

private:
    template <class> friend class BSTIteratorBase;
    template <class> friend class BinarySearchTree;

    T value_;
    node_pointer leftPtr_;
    node_pointer rightPtr_;
};

2 个答案:

答案 0 :(得分:0)

如果value_type的封闭类型为const,则可以使用metafunction

template<class T>
struct ValueTypeOf { 
    typedef typename T::value_type type; 
};

template<class T>
struct ValueTypeOf<T const> {
    typedef typename T::value_type const type; 
};

template <typename Node>
class BSTIteratorBase : public boost::iterator_facade<
    BSTIteratorBase<Node>,
    typename ValueTypeOf<Node>::type,
    boost::forward_traversal_tag
>
// ...

答案 1 :(得分:0)

我倾向于写

typedef BSTIteratorBase<BSTNode<T>>               iterator;
typedef BSTIteratorBase<const BSTNode<const T>>   const_iterator;
                                      ^-- note extra const

请注意,这很好地反映了T ** - &gt; const T *const *转型。