I didn't want to repeat the same code so I casted to const. Here is a
simplified example of when casting to const can help avoid code duplication:
class MyClass
{
int numbers[50];
public:
// default constructor not shown
int &find_largest()
{
return ((const MyClass &)*this).find_largest();
}
const int &find_largest() const; // implementation not shown
};
Should I be doing this? Is there a better way?
I wanted to do this in another situation but it doesn't look possible. Here
it is:
class MyOtherClass
{
std::vector<int> numbers;
public:
// default constructor not shown
void find_even(std::vector<int *> &even) {
for (std::vector<int>::size_type i=0; i < numbers.size(); i++) {
if (numbers[i] % 2)
even.push_back(&numbers[i]);
}
}
void find_even(std::vector<const int *> &even) const {
for (std::vector<int>::size_type i=0; i < numbers.size(); i++) {
if (numbers[i] % 2)
even.push_back(&numbers[i]);
}
}
};
Notice that the code in both methods is exactly the same. How do I avoid
this kind of duplication? Thanks.