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

<strong>Possible Duplicate:</strong> 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?

Answer1:

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]; }

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:How to avoid operator's or method's code duplication for const and non-const objects? [dup