0

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).

jimifiki
  • 5,377
  • 2
  • 34
  • 60
  • You don't need the non-const version. The compiler will call the const version for non-const objects as well as const objects. Don't know about compilers on AIX, but unless you've got code that shows that there is a problem it's really not possible to diagnose it. – Pete Becker Dec 19 '13 at 13:20

2 Answers2

2

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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
2

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);
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644