Re: const_cast needed for lookup in STL containers?
davidbaraff@gmail.com wrote:
std::set<Item*> itemSet;
bool DoSomeChecking(const Item* ptr) {
if (itemSet.count(ptr) > 0) // XXX doesn't compile: needs
const_cast<>
...
}
set::count() takes an element of the set, and 'ptr' is not convertible to
such an element.
So the compiler complains that it can't turn an Item* into a Item
const* without a cast. I understand that.
Exactly.
Question: if I keep containers of non-const pointers around, and I
happen to have a const-such version of a pointer on my hands, how do I
look it up (without a const_cast of course).
Well, since you can see in this situation that it won't change what the
argument points to, a const_cast resolves the issue pretty clearly. To
simply search the sequence would require more CPU, so I would indeed go for
the well-justified const_cast.
A third alternative would be the (yet unreleased) STLport 5.1 where count()
and some other functions are in fact templated on the argument type and
where the argument type only has to be comparable to the element type. This
is an extension though and not standard C++. See the documentation for more
info.
Or am I missing a larger issuer here?
No, I think it's just unfortunate.
Uli
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]