How to avoid operator's or method's code duplication for const and non-const objects? [duplicate]

不问归期 提交于 2019-12-12 16:47:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!