octoploid octoploid - 1 year ago 74
C++ Question

Why does std::tuple decompose into rvalue references

Why does std::tuple decompose into rvalue references?

#include <tuple>

template <typename, typename> struct same_type;
template <typename T> struct same_type<T, T> {};

void foo() {
std::tuple tuple(1, 'a', 2.3, true);
auto[i, c, d, b] = tuple;
same_type<decltype(i), int &&>{};
same_type<decltype(c), char &&>{};
same_type<decltype(d), double &&>{};
same_type<decltype(b), bool &&>{};

This compiles without error using gcc trunk.
I would have expected the plain types instead, e.g.

same_type<decltype(i), int>{};

Live example

Answer Source

From this decomposition reference:

Each identifier becomes a variable whose type is reference to std::tuple_element<i,E>::type: lvalue reference if its corresponding initializer is an lvalue, rvalue reference otherwise.

You have a tuple of rvalues, therefore you get rvalue references.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download