且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该什么时候std ::转发一个函数调用?

更新时间:2022-12-08 10:25:24

A better description of what std::forward<decltype(func)>(func)(...) is doing would be preserving the value category of the argument passed to the lambda.

Consider the following functor with ref-qualified operator() overloads.

struct foo
{
    void operator()() const &&
    { std::cout << __PRETTY_FUNCTION__ << '\n'; }

    void operator()() const &
    { std::cout << __PRETTY_FUNCTION__ << '\n'; }
};

Remember that within the body of the lambda func is an lvalue (because it has a name). If you didn't forward the function argument the && qualified overload can never be invoked. Moreover, if the & qualified overload were absent, then even if the caller passed you an rvalue foo instance, your code would fail to compile.

Live demo