我有一个这样的课程,
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_ref
但iterator
返回可修改的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_;
};
答案 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 *
转型。