I'm considering this question on const and non-const class methods. The preferred answer is taken from Effective C++ by Scott Meyers, where the non-const method is implemented in terms of the const method.
Extending this further, how can code duplication be reduced if the methods return iterators instead of references? Modifying the example in the linked question:
class X
{
std::vector<Z> vecZ;
public:
std::vector<Z>::iterator Z(size_t index)
{
// ...
}
std::vector<Z>::const_iterator Z(size_t index) const
{
// ...
}
};
I can't implement the non-const method in terms of the const method because it's not possible to convert directly from a const_iterator to an iterator without using the distance()/advance() technique.
In the example, because we're using a std::vector as the container, it might actually be possible to cast from a const_iterator to an iterator because they may well be implemented as pointers. I don't want to rely on this. Is there a more general solution?
There are a couple tricks you can use. You can turn a const_iterator into an iterator if you have non-const access to the container. (which you do):
std::vector<Z>::iterator Z(size_t index)
{
std::vector<Z>::const_iterator i = static_cast<const X&>(*this).Z(index);
return vecZ.erase(i, i);
}
You could also do this:
std::vector<Z>::iterator Z(size_t index)
{
return std::next(vecZ.begin(), std::distance(vecZ.cbegin(), static_cast<const X&>(*this).Z(index)));
}
Neither are particularly elegant. Why don't we have a const_iterator_cast
like const_pointer_cast
? Maybe we should.
EDIT, I missed the most obvious and elegant solution because I was trying to use the const method from the non-const method. Here I do the opposite:
std::vector<Z>::const_iterator Z(size_t index) const
{
return const_cast<X&>(*this).Z(index);
}
You are dereferencing the result of const_cast
however this is not undefined behavior as long as the non-const Z
does not modify any data in X
. Unlike the other 2 solutions I gave, this is one I might use in practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With