I am wondering why std::apply
does not forward rvalue-reference
when working with reference types in tuples (see 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));
}
The root cause for this is std::get
and the reference collapsing rule.
Wouldn't it make more sense if std::apply
internally would use this 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);
}
}
which would result in a perfect forward for
std::apply([](auto&& arg){/*arg is here `int&&`*/}, t);