I have two longish blocks of code that are identical except in various comparative statements >
is switched with <
, >=
with <=
etc. I wanted to put these in a function and use one operator or another depending on a function input.
I am coding in MQL5 but this is very similar to C++ so hopefully methods that work in this will also be useable in my case.
You can create a comparator function for each comparison you need, and then pass the right function as an argument to the longish code blocks (wrapped in a suitably defined function)
As an example, consider the following hypothetical case where a function (myFunc
) receives 2 integers(a
and b
)
and processes them. The processing steps are similar except for the type of comparison done on the arguments. We get around the problem by providing myFunc
with the right tool for comparison.
#include <iostream>
using namespace std;
bool comp1(int a, int b) {
return a > b;
}
bool comp2(int a, int b) {
return a < b;
}
void myFunc(int a, int b, bool (*myComp)(int, int)) {
bool res = myComp(a, b);
cout << "value : " << res << endl;
}
int main()
{
myFunc(1, 2, comp1); //use >
myFunc(1, 2, comp2); //use <
return 0;
}
Clearly, comp1
and comp2
are the 2 different comparators. We pass one of them to myFunc
depending on the requirements (<
or >
).
The best thing is that your comparisons can now be as complex as you want, and myFunc
is oblivious to the complexities.