C++ const-cast a reference

298 views Asked by At

Is this correct? It compiles with my compiler but I've been told it doesn't with an AIX one.

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? (Beside reimplement the non const version with Ctrl-C Ctrl-V).

2

There are 2 answers

0
Ivaylo Strandjev On BEST ANSWER

const_cast is used to remove const-ness of a variable. That is if you have const A& a you can write A& b = const_cast<A&>(a). Now you will be able to modify b or call non-const methods on it.

In this case you construct a const_iterator from a regular iterator and this is always possible even without using a 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.

0
Mike Seymour On

iterator and const_iterator are (in general) different types, so you can't cast references. However, iterator is convertible to const_iterator, so you could do

return funct(static_cast<ConstIterator>(iter));

or, more safely since it only allows explicit conversions:

ConstIterator citer = iter;
return funct(citer);