0

我想知道为什么在使用元组中的引用类型时std::apply不转发rvalue-reference(参见Live):

#include <type_traits>
#include <tuple>

template<typename T>
void assertRvalueReference(T&& t)
{   
    static_assert(std::is_rvalue_reference_v<decltype(t)>, "Ups"); 
}

int main()
{
    struct A{};
    A a;
    int v;
    auto t = std::tuple<A&&, int>(std::move(a), v); // essentially `std::forward_as_tuple(v, std::move(a))`

    std::apply([](auto&& arg, ...)
               {
                   assertRvalueReference(std::forward<decltype(arg)>(arg)); 
               }, std::move(t));

    std::apply([](auto&& arg, ...)
               {
                   // assertRvalueReference(arg); // This should in my opinion not fail
               }, t);

    assertRvalueReference(non_std_get<0>(t)); 
}

造成这种情况的根本原因是std::get参考折叠规则。std::apply如果在内部使用它不是更有意义吗non_std_get


template<std::size_t Index, typename Tuple>
constexpr decltype(auto) non_std_get(Tuple&& t)
{
    using Type = std::tuple_element_t<Index, std::remove_cvref_t<Tuple>>;
    if constexpr(std::is_rvalue_reference_v<Type>)
    {
        return std::move(std::get<Index>(t));
    }
    else
    {
        return std::get<Index>(t);
    }
}

这将导致一个完美的前锋

std::apply([](auto&& arg){/*arg is here `int&&`*/}, t);
4

1 回答 1

0

The problem is not in std::apply, it is in your lambda.

Inside your lambda, arg is always an lvalue. You need to explicitly cast it to an rvalue with std::forward in order to make it an rvalue.

于 2020-01-03T13:38:04.180 回答