callback vs lambda

前端 未结 4 1999
予麋鹿
予麋鹿 2021-02-05 04:20

Suppose I have the following code that I wish to refactor:

int toFuture()
{
  precalc();
  int calc = 5 * foobar_x() + 3;
  postcalc();
  return calc;
}

int toP         


        
4条回答
  •  迷失自我
    2021-02-05 04:49

    There is a C/C++ way to do this, and a C++11 way. Neither way involves lambdas or templates.

    The C/C++ way:

    double MyFunc (int x, float y) { return x + y ; }
    
    int main()
      {
      double (*pf) (int, float) ;
      pf = MyFunc ;
      pf (101, 202.0) ;
      }
    

    The C++11 way:

    #include 
    
    double MyFunc (int x, float y) { return x + y ; }
    
    int main()
      {
      std::function f ;
      f = MyFunc ;
      f (51, 52.0) ;
      }
    

    In either case, you just pass pf or f to your refactored function as a parameter. Using lambdas or templates is overkill here.

提交回复
热议问题