callback vs lambda

前端 未结 4 1950
予麋鹿
予麋鹿 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:38

    One approach:

    template
    int perform_calc(CalcFuncT&& calcfunc)
    {
        precalc();
        int const calc = std::forward(calcfunc)();
        postcalc();
        return calc;
    }
    
    int main()
    {
        perform_calc([]{ return 5 * foobar_x() + 3; }); // toFuture
        perform_calc([]{ return 5 * foobar_y() - 9; }); // toPast
    }
    

提交回复
热议问题