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?
return vecZ.begin() + index
. Or, if you absolutely must make them different, the const version could bereturn vecZ.cbegin() + index
. Look ma, no duplication!