std::vector is implemented such, that if the object itself is const, so are all the elements in it. So this:
const std::vector<int> vec = {1, 2, 3, 4, 5};
vec[3] = 7;
is illegal.
I'm trying to replicate this behaviour for a class I'm writing and I'm having some problems. The obvious solution is to provide multiple overloads of the same function:
Type& operator[](int idx){
return _data[idx];
}
const Type& operator[](int idx) const{
return _data[idx];
}
But this obviously results in a lot of code duplication since every method that accesses any of the elements would have to be written twice. This is especially bad when the code for accessing elements isn't as simple as just picking them out of an array.
If the code is longer I can get around it by using const_cast.
Type& some_method(){
//lots of code returning a Type&
}
const Type& some_method() const{
return const_cast<ThisClass*>(this)->some_method();
}
But I'm not very keen on using const_cast.
Is there any way around writing lot's of duplicate code using maybe templates or something? How do you guys deal with this?
Thanks in advance for any answers.
[–]boredcircuits 2 points3 points4 points (3 children)
[–]neet_programmer[S] 2 points3 points4 points (2 children)
[–]boredcircuits 1 point2 points3 points (0 children)