gpt4 book ai didi

c++ - 当参数是参数包时,右值引用不起作用

转载 作者:行者123 更新时间:2023-12-02 10:05:13 25 4
gpt4 key购买 nike

当我从模板参数包中创建一个右值时,它不会编译,但如果它是一个“简单”模板参数,它编译得很好。

在此代码 for_each_in_tup1编译正常,但 for_each_in_tup3才不是。我不明白为什么这不会编译,但 GCC 9.2 和 VC v142 都同意这是错误的。

为什么这不是有效的语法?

这个例子:

#include <tuple>
using namespace std;

template< typename Tuple, size_t N = 0>
void for_each_in_tup1( Tuple&& tup ) {
if constexpr(N < tuple_size<decay_t<Tuple>>::value)
for_each_in_tup1<Tuple, N + 1>(forward<Tuple>(tup));
}

template< template<typename...> typename Tuple, typename... Ts>
void for_each_in_tup2( const Tuple<Ts...>& tup) {
}

template< template<typename...> typename Tuple, typename... Ts>
void for_each_in_tup3( Tuple<Ts...>&& tup) {
}

void test_lazy() {
tuple<uint32_t, uint32_t> tup;
for_each_in_tup1(tup);
for_each_in_tup2(tup);
for_each_in_tup3(tup);
}

失败:
<source>:20:22: error: cannot bind rvalue reference of type 'std::tuple<unsigned int, unsigned int>&&' to lvalue of type 'std::tuple<unsigned int, unsigned int>'
20 | for_each_in_tup3(tup);
| ^~~

<source>:15:39: note: initializing argument 1 of 'void for_each_in_tup3(Tuple<Ts ...>&&) [with Tuple = std::tuple; Ts = {unsigned int, unsigned int}]'
15 | void for_each_in_tup3( Tuple<Ts...>&& tup) {
| ~~~~~~~~~~~~~~~^~~

godbolt

最佳答案

for_each_in_tup1您正在使用转发引用:

template< typename Tuple, size_t N = 0>
void for_each_in_tup1( Tuple&& tup )

当你传递左值时, Tuple推导出为 Tuple& , 在引用折叠后你会得到 for_each_in_tup1(Tuple&) .左值可以绑定(bind)到左值引用,这就是这段代码有效的原因。如果您将右值传递给 for_each_in_tup1 , 参数为 Tuple&& ,并且它只能接受右值。

for_each_in_tup3有正常的右值引用,它只能绑定(bind)右值。
调用 for_each_in_tup3你必须投 tup右值,例如 std::move :
for_each_in_tup3(std::move(tup));

关于c++ - 当参数是参数包时,右值引用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60533112/

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