[英]C++ const-cast a reference
Is this correct? 这个对吗? It compiles with my compiler but I've been told it doesn't with an AIX one. 它可以使用我的编译器进行编译,但是有人告诉我它不使用AIX。
typedef std::vector<Entry>::iterator Iterator;
typedef std::vector<Entry>::const_iterator ConstIterator;
bool funct(ConstIterator& iter) const;
inline bool funct(Iterator& iter){return funct(const_cast<ConstIterator&>(iter));}
What should I do to let my code compile on the AIX platform? 我应该怎么做才能使我的代码在AIX平台上编译? (Beside reimplement the non const version with Ctrl-C Ctrl-V). (除了使用Ctrl-C Ctrl-V重新实现非const版本外)。
const_cast
is used to remove const-ness of a variable. const_cast
用于删除变量的常数。 That is if you have const A& a
you can write A& b = const_cast<A&>(a)
. 也就是说,如果您具有const A& a
,则可以编写A& b = const_cast<A&>(a)
。 Now you will be able to modify b
or call non-const methods on it. 现在,您将可以修改b
或对其调用非常量方法。
In this case you construct a const_iterator
from a regular iterator
and this is always possible even without using a const_cast
. 在这种情况下,您可以从常规iterator
构造const_iterator
,即使不使用const_cast
也总是可能的。 Keep in mind these are two different types and simply const_iterator
happened to be constructable from iterator
C++ const-ness does not have much to do in this case. 请记住,这是两种不同的类型,而const_iterator
恰好是可以从iterator
构造的,在这种情况下,C ++ const-ness没什么要紧的。
iterator
and const_iterator
are (in general) different types, so you can't cast references. iterator
和const_iterator
(通常)是不同的类型,因此您不能转换引用。 However, iterator
is convertible to const_iterator
, so you could do 但是, iterator
可转换为const_iterator
,因此您可以执行
return funct(static_cast<ConstIterator>(iter));
or, more safely since it only allows explicit conversions: 或者,更安全,因为它仅允许显式转换:
ConstIterator citer = iter;
return funct(citer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.