Is there any good way to obviate the const_cast
below, while keeping const correctness?
Without const_cast
the code below doesn't compile. set::find
gets a const reference to the set's key type, so in our case it guarantees not to change the passed-in pointer value; however, nothing it guaranteed about not changing what the pointer points to.
class C {
public:
std::set<int*> m_set;
bool isPtrInSet(const int* ptr) const
{
return m_set.find(const_cast<int*>(ptr)) != m_set.end();
}
};
bool
, this code does not currently compile. Did you mean to usereturn m_set.find(const_cast<int*>(ptr)) != std::cend(m_set);
? – Greenwichstd::find
could help. I wonder if they ever partly specialize it to run in logarithmic time onstd::set
bounds. – Pliske