Pergunta

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. That is why I had to keep the const_cast<value_type&>() part. How can I make sure that const_iterator return a const_ref but iterator returns a modifiable ref? Here are the relevant typedefs,

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_;
};
Foi útil?

Solução

You can use a metafunction that constifies value_type if its enclosing type is const:

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

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top