callback vs lambda

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

    If you are wanting a template approach using C++11 features, that could look as simple as:

    template
    auto calculation(FuncType&& func) -> decltype(func())
    {
        precalc();
        auto ret = func();
        postcalc();
        return ret;
    }
    

    You would then simply call your calculation function and pass it either a lambda, a functor, or a function-pointer. Your only souce of difficulty in this instance would be if you passed a function that had a void return-type ... in that case you will get a compiler error (which is a good thing vs. a runtime error).

提交回复
热议问题