feelfree feelfree - 1 year ago 89
C++ Question

How to perform operator overloading to avoid if condition in c++?

I give the following example to illustrate my question:

bool bSign;
// bSign will be set depending on some criteria, which is omitted here.
// b[][][] is a float array, which is initialized in the program
for(int i=0; i<1000; i++)
for(int j=0; j<10000; j++)
for(int k=0; k<10000; k++)
a[i][j][k] = (b[i][j][k]>500);
a[i][j][k] = (b[i][j][k]<500);

In the above codes, I have to rely on
to design the kind of operator (
) I should use to set the output variable
. However, I found it costly as it is done within a long
loop. Any ideas on how I can escape that?

Answer Source

As many people said, it is better to move if statement out of loops (if it is possible). To prevent code duplication, you can use function pointers, but it may be worse if there will be real calls. Calls cost more than simple if. If compiler can inline them, it will be ok.

You also can use templates metaprogramming (simple template algorithm in this case) on this manner:

 template<typename ComparatorT>
 void doTheWork(float ***a, const float ***b, ComparatorT comparator)
     for(int i=0; i<1000; i++)
         for(int j=0; j<10000; j++)
             for(int k=0; k<10000; k++)
                 a[i][j][k] = comparator(b[i][j][k], 500);

 // Usage.
 bool bSign;
 if (bSign) {
     doTheWork(a, b, std::greater<float>());
 } else {
     doTheWork(a, b, std::larger<float>());

Compiler can inline comparator's calls (it is much easier than with function pointers) and it will work almost like you wrote two different loops. The comparator object can be really created, but usually it is not significant. One disadvantage is that it often produces hard-to-read code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download