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_iteratoraを返すconst_refiteratormodifiableを返すようにするにはどうすればよい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

私は書きたいと思います

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 に答える
0

囲んでいる型が 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
>
// ...
于 2012-09-19T08:10:08.910 に答える