问题
Possible Duplicate:
How do I remove code duplication between similar const and non-const member functions?
My task is to implement c++ vector analogue. I've coded operator[] for 2 cases.
T myvector::operator[](size_t index) const {//case 1, for indexing const vector
return this->a[index];
}
T & myvector::operator[](size_t index) {//case 2, for indexing non-const vector and assigning values to its elements
return this->a[index];
}
As you can see, the code is completely equal. It's not a problem for this example (only one codeline), but what should I do if I need to implement some operator or method for both const and non-const case and return const or reference value, respectively? Just copy-paste all the code everytime I make changes in it?
回答1:
One of the few good uses of const_cast here. Write your non const function as normal, then write your const function like so:
const T & myvector::operator[](size_t index) const {
myvector<T> * non_const = const_cast<myvector<T> *>(this);
return (*non_const)[index];
}
来源:https://stackoverflow.com/questions/5735287/how-to-avoid-operators-or-methods-code-duplication-for-const-and-non-const-obj