Function to Lambda

后端 未结 2 784
清酒与你
清酒与你 2021-02-06 18:54

It\'s often useful in C++ to work with lambdas and function objects, rather than function pointers. The reason being that a lambda\'s or function object\'s type fully encodes wh

2条回答
  •  长情又很酷
    2021-02-06 19:28

    If you just want to wrap a function pointer in a function object, I'd recommend a macro:

    #define WRAP_FN(f) [](auto&&... args) -> decltype(auto) { \
        return f(std::forward(args)...); };
    

    To be used like:

    auto lam = WRAP_FN(foo);
    

    The advantage of the macro is that it'll additionally handle overloaded names - so that you can pass overloaded functions into std algorithms and have that do what you want it to.

提交回复
热议问题