gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:32:12 25 4
gpt4 key购买 nike

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

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

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

最佳答案

您必须使用 std::forward 以保留 fn() 参数的值类别。由于参数在 fn 中有一个名称,它们是左值,并且在没有 std::forward 的情况下,它们将始终照原样传递给 std::forward_as_tuple

可以使用 following example 来证明差异:

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);
}

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

foo f;
bar1(f);
std::cout << "--------\n";
bar1(foo{});

输出:

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

从输出中可以看出,在这两种情况下,都没有使用 std::forward,参数作为左值传递给 bar2

关于C++11 std::forward_as_tuple 和 std::forward,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25427938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com