【发布时间】:2015-02-19 16:28:04
【问题描述】:
我正在编写一个 STL 风格的“树”容器类。我目前使用具有以下习语的单个类支持 const 和非 const 迭代器:
template<typename T>
class Tree
{
public:
using iterator = TreeIterator<T, false>;
using const_iterator = TreeIterator<T, true>;
// ...
};
TreeIterator 是这样的:
template <typename T, bool is_const_iterator/* = true*/>
class TreeIterator : public std::iterator<std::forward_iterator_tag, T>
{
public:
// TreeNodePointer is either a const or non-const pointer depending on the template parameter.
typedef typename std::conditional<is_const_iterator, const TreeNode<T>*, TreeNode<T>*>::type TreeNodePointer;
// All the iterator interface and typedefs...
private:
TreeNodePointer m_pointer; // internal pointer.
};
问题是,为了保持我的“STL 风格”,insert_hint 或emplace_hint 之类的操作应该将const_iterator 参数作为输入,但我需要定义从iterator 到const_iterator 的隐式转换按照用户的预期工作。
我很确定从 const iterator 隐式转换为 const_iterator 应该没问题,但我不确定在语法上如何做到这一点。对我来说,在模板(或其他机制)上设置某种条件来阻止 const_iterator 转换为 iterator 也很重要。
如何定义这样的转换?
【问题讨论】:
标签: c++ c++11 stl iterator const-iterator