Lets say i have two functions inside a class:
vector<int> getAllPossibleNumbers() {
vector<int> nums;
for (int i=0; i < MAX; i++)
if (isAPossibleNumber(i))
nums.push_back(i);
return nums;
}
bool hasAtLeastOnePossibleNumber() {
for (int i=0; i < MAX; ++i)
if (isAPossibleNumber(i))
return true;
return false;
}
I could rewrite the second function as
bool hasAtLeastOnePossibleNumber() {
return getAllPossibleNumbers().size() > 0;
}
But it's obvious, especially with a very high MAX number, how the first is much more efficent.
So, how can I avoid code duplication of this kind?
I would prefer a general solution, that can work with more complicated functions and can compile with C++11.
One option would be to move most of the logic into a third function with a callback to the outer functions which gives the numbers. The result of the callback can be used to determine whether to continue the loop:
template <typename Callback>
void checkNumbers(Callback callback)
{
for (int i=0; i < MAX; i++)
{
if (isAPossibleNumber(i))
{
if (!callback(i))
{
break;
}
}
}
}
std::vector<int> getAllPossibleNumbers() {
std::vector<int> nums;
checkNumbers([&](int i){ nums.push_back(i); return true; });
return nums;
}
bool hasAtLeastOnePossibleNumber() {
bool result = false;
checkNumbers([&](int i){ result = true; return false; });
return result;
}
The extra function should be optimised away by modern compilers.