I have a class, say, vector<T>. I want to implement two getter methods, returning T& and const T& respectively. I do not want to implement both of them. Instead I'd like to implement only const version and then reuse its code in a non-const method with const_cast.
template<typename T>
class Vector {
public:
T& operator[](size_t i) {
return const_cast<T&>(
static_cast<const Vector<T>*>(this)->operator[](i));
}
const T& operator[](size_t i) const {
return data[i];
}
private:
T* data;
};
What are the possible pitfalls of this approach? Or, are there any methods to check that const_cast is legitimate in any exact case?
Finally, what are the good common ways to deal with such duplicated const/non-const code?
One clean way is to delegate to a private template function which can deduce the constness of this:
#include <cstdint>
template<typename T>
class Vector {
public:
T& operator[](std::size_t i) {
return impl_indirection(this, i);
}
const T& operator[](std::size_t i) const {
return impl_indirection(this, i);
}
private:
template<class MaybeConstVector>
static decltype(auto) impl_indirection(MaybeConstVector* pv, std::size_t index)
{
return pv->data[index];
}
T* data;
};
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