When should I std::forward a function call?

后端 未结 1 1350
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 12:22

A code snippet I saw in Effective Modern C++ has a clever implementation of the instrumentation rationale to create a function timer :

<         


        
相关标签:
1条回答
  • 2020-12-29 12:48

    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

    0 讨论(0)
提交回复
热议问题