Consider below functions
f(int a[])
{
///CODE
for
for
if(a[i] > 0)
//change i on some condition
for
//CODE
if(a[i] > 0)
///CODE
}
f(int a[], int th)
{
///CODE
for
for
if(a[i] < th)
//change i on some condition
for
//CODE
if(a[i] < th)
///CODE
}
So we have f function with a optimized huge body,
several lines are the same: if(a[i] > 0)
I want to add extend this function so that if a parameter is added, those lines should change to if(a[i] < th)
When I overload the function, hundreds of line is duplicated (becomes hard to maintain), so i don’t want this. Also I cannot divide the body into functions because “the line” appears in too many inner loops.
First idea:
f(int a[], int th = -1)
{
///CODE
if(th == -1)
if(a[i] > 0)...
else
if(a[i] < th)...
///CODE
}
I cannot do this because of the performance overhead of introducing the additional if to the inner loop.
Is there a way to solve it both efficiently and clearly, perhaps using templates or macros?
You can pass functions via template arguments:
You can then use
flike this: