C ++ STL使用红黑树在std::set
和std::map
内部存储数据。我注意到set::iterator
实际上是红黑树的const迭代器的typedef:
//All code snippets taken from SGI STL. https://www.sgi.com/tech/stl/
typedef _Rb_tree<key_type, value_type, _Identity<value_type>, key_compare, _Alloc> _Rep_type;
typedef typename _Rep_type::const_iterator iterator;
这是合理的,因为应该假定用户不要通过迭代器来修改集合的内容。但是set
必须实现insert
和erase
之类的操作,它们需要红黑树的非常量迭代器。 SGI STL使用c样式强制转换来做到这一点:
void erase(iterator __position) {
typedef typename _Rep_type::iterator _Rep_iterator;
_M_t.erase((_Rep_iterator&)__position);
}
我想知道:
_Rep_type::const_iterator
强制转换为_Rep_type::iterator&
。static_cast
和const_cast
均不起作用。 reinterpret_cast
可以编译,但是我不确定它是否与C样式强制转换相同。iterator
和_Rep_type::iterator
是相同类模板的实例,前者使用const
限定类型,而后者使用相同但非const
的类型。像这样的东西:
template <class T, class U>
struct B {};
using S = B<int&, int*>;
using Sconst = B<const int&, const int*>;
因此,您的问题是:
static_cast
,因为编译器认为类型不相关。您必须携带重型大炮,reinterpret_cast
:int test() {
S s;
Sconst& sconst = reinterpret_cast<Sconst&>(s);
}