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?