C++ 11 std :: forward_as_tuple和std :: forward

tow*_*120 8 c++ templates tuples perfect-forwarding c++11

std::forward当我将它们用作参数时,我应该使用我的函数参数std::forward_as_tuple吗?

template<class ... List>
void fn(List&& ... list){
   // do I need this forward?
   call_fn( forward_as_tuple( forward<List>(list)... ) );  
}
Run Code Online (Sandbox Code Playgroud)

我知道它们将被存储为右值引用,但还有什么我应该考虑的吗?

Pra*_*ian 7

您必须使用std::forward以保留参数的值类别fn().由于参数在其中具有名称fn,因此它们是左值,并且std::forward它们将始终如此传递给它们std::forward_as_tuple.

可以使用以下示例演示差异:

template<typename T>
void bar2(T&& t)
{
    std::cout << __PRETTY_FUNCTION__ << ' '
               << std::is_rvalue_reference<decltype(t)>::value << '\n';
}

template<typename T>
void bar1(T&& t)
{
    std::cout << __PRETTY_FUNCTION__ << ' '
              << std::is_rvalue_reference<decltype(t)>::value << '\n';
    bar2(std::forward<T>(t));
    bar2(t);
}
Run Code Online (Sandbox Code Playgroud)

bar1总是将参数传递给bar2,一次使用std::forward,一次不使用.现在让我们用左值和右值参数调用它们.

foo f;
bar1(f);
std::cout << "--------\n";
bar1(foo{});
Run Code Online (Sandbox Code Playgroud)

输出:

void bar1(T&&) [with T = foo&] 0
void bar2(T&&) [with T = foo&] 0
void bar2(T&&) [with T = foo&] 0
--------
void bar1(T&&) [with T = foo] 1
void bar2(T&&) [with T = foo] 1
void bar2(T&&) [with T = foo&] 0
Run Code Online (Sandbox Code Playgroud)

正如您在输出中看到的那样,在不使用的情况下,std::forward参数将作为左值传递给bar2.