1

我有这样的课,

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。这就是为什么我必须保留这const_cast<value_type&>()部分。如何确保const_iteratorreturn aconst_refiterator返回 modifiable 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_;
};
4

2 回答 2

0

您可以使用一个元函数来约束value_type其封闭类型是否为 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
>
// ...
于 2012-09-19T08:10:08.910 回答
0

我会倾向于写

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

请注意,这很好地反映了T **->const T *const *转换。

于 2012-09-19T09:02:57.800 回答