如何避免重复

Vol*_*kan 0 c++ macros performance templates overloading

考虑以下功能

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
}
Run Code Online (Sandbox Code Playgroud)

所以我们有f函数和一个优化的巨体,几行是相同的:if(a [i]> 0)我想添加扩展这个函数,这样如果添加一个参数,那些行应该改为if(a [ i] <th)当我重载函数时,数百行重复(变得难以维护),所以我不想要这个.此外,我不能将身体划分为函数,因为"行"出现在太多的内部循环中.

第一个想法:

f(int a[], int th = -1)
{
     ///CODE
        if(th == -1)
            if(a[i] > 0)...
        else
            if(a[i] < th)...
     ///CODE
}
Run Code Online (Sandbox Code Playgroud)

我不能这样做是因为将额外的if引入内循环的性能开销.有没有办法有效和清晰地解决它,也许使用模板或宏?

Bjö*_*lex 6

您可以尝试将其设为一个采用任意谓词的函数模板.如果谓词很简单,就像你的情况一样,你可以依靠编译器来内联它,这样就不会有效率的损失.您应该分析您的应用程序以验证它.代码可能如下所示:

template<class Pred>
void f(int a[], Pred pred) {
 ///CODE
 for
  for
   if(pred(a[i]))
   //change i on some condition
 for
    //CODE
    if(pred(a[i]))
///CODE
}
Run Code Online (Sandbox Code Playgroud)

Pre-C++ 11你必须将函子或函数指针作为谓词传递,在C++ 11中你可以使用lambdas:

f(data, [](int val){ return val > 0; });
f(data, [th](int val){ return val < th; });
Run Code Online (Sandbox Code Playgroud)