简体   繁体   English

使用boost :: iterator_facade <>返回迭代器的ref,但是返回const_iterator的const_ref呢?

[英]Return ref for iterator but const_ref for const_iterator using boost::iterator_facade<>?

I have a class like this, 我有这样的课

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 does not depend on the constness of the BSTNode class. value_type不依赖于的常量性 BSTNode类。 That is why I had to keep the const_cast<value_type&>() part. 这就是为什么我必须保留const_cast<value_type&>()部分的原因。 How can I make sure that const_iterator return a const_ref but iterator returns a modifiable ref ? 如何确定const_iterator返回const_refiterator返回可修改的ref Here are the relevant typedefs, 这是相关的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;

And the node class, 还有节点类

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_;
};

You can use a metafunction that constifies value_type if its enclosing type is const: 如果封闭值类型为const,则可以使用用于构造value_type函数:

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
>
// ...

I'd be inclined to write 我倾向于写

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

Note that this nicely mirrors the T ** -> const T *const * transformation. 注意,这很好地反映了T ** -> const T *const *转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM