Is there a one-liner to unpack tuple/pair into references?

Fortunately, C++17 has a solution for exactly this problem, the structured binding declaration. Even the non-reference interface can be improved.

auto[x, y, z] = g[i];

The above line declares x, y,z and initializes them with the values of g[i]. Not only is it cleaner, but it could be more efficient for types that are expensive to construct.

To get references to the members of g[i], one can write

auto& [x, y, z] = g[i];

You can automate it with a function so that you don’t have to type out 3 (or more) lines:

template <class... Ts, std::size_t... Is, class Tuple>
decltype( auto ) tie_from_specified( std::index_sequence<Is...>, Tuple& tuple )
{
    return std::tuple<Ts...>{ std::get<Is>( tuple )... };
}

template <class... Ts, class Tuple>
decltype( auto ) tie_from( Tuple& tuple )
{
    return tie_from_specified<Ts...>( std::make_index_sequence<sizeof...( Ts )>{}, tuple );
}

Usage would be:

int x{ 2 };
std::tuple<int, int&, int> g19( 1, x, 3 );

// new tuple: ref to get<0>( g19 ), value of get<1>( g19 ), ref to get<2>( g19 )
auto t0{ tie_from<int&, int, int&>( g19 ) };

// new tuple: ref to get<0>( g19 ), ref to get<2>( g19 )
auto t1{ tie_from_specified<int&, int&>( std::index_sequence<0, 2>{}, g19 ) };

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)