我有这样的课,
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_iterator
return aconst_ref
但iterator
返回 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_;
};