is any difference between std::forward and std::forward?

前端 未结 2 1708
天涯浪人
天涯浪人 2020-12-15 05:33

are these functions equivalent?

template 
void foo(T && t)
{
    bar(std::forward(t));
}

template 
void foo2(         


        
2条回答
  •  温柔的废话
    2020-12-15 06:21

    The accepted answer does not solve the problem in title completely.

    A macro argument preserves the type of the expression. A forwarding parameter in a template does not. This means t in foo2 (as a forwarding function parameter) has the type T&& (because this is the forwarding template parameter), but it can be something different when the macro is in other contexts. For example:

    using T = int;
    T a = 42;
    T&& t(std::move(a));
    foo(MY_FORWARD(t)); // Which foo is instantiated?
    

    Note here t is not an xvalue, but an lvalue. With std::forward(t), which is equivalent to std::forward(t), t would be forwarded as an lvalue. However, with MY_FORWARD(t), which is equivalent to std::forward(t), t would be forwarded as an xvalue. This contextual-dependent difference is sometime desired when you have to deal with some declared variables with rvalue reference types (not forwarding paramter even they may look like similar in syntax).

提交回复
热议问题