Ivan Sanz Carasa
Ivan Sanz Carasa

Reputation: 1387

perfect forwading tuple values from std::get

I have a nice implementation similar to std::apply that expands a tuple as arguments for a function. It works perfectly, except that std::get is always returning an lvalue and it fails to match the proper overload.

POC code can be found here: https://wandbox.org/permlink/OUYMQY2afL8vRMUu

The idea is to add std::forward to apply_sequence so it prints ONE TWO THREE

void printNumber(const int& x, const int& y)
{
    std::cout << "ONE" << std::endl;
}

void printNumber(const int& x, int&& y)
{
    std::cout << "TWO" << std::endl;
}

void printNumber(int&& x, const int& y)
{
    std::cout << "THREE" << std::endl;
}

template<typename... TTuple, std::size_t... Indices>
auto apply_sequence(const std::tuple<TTuple...>& tuple, std::index_sequence<Indices...>)
{
    // missing: forward value to proper type (currently is always lvalue)
    return printNumber(std::get<Indices>(tuple)...);
}

template<typename... TTuple>
auto apply_tuple(const std::tuple<TTuple...>& tuple)
{
    return apply_sequence(tuple, std::index_sequence_for<TTuple...>());
}

int main(int argc, char* argv[])
{
    std::tuple<int, int> one { 1, 2 };
    apply_tuple(one); // ONE

    std::tuple<int, int&&> two { 1, 2 };
    apply_tuple(two); // TWO

    std::tuple<int&&, int> three { 1, 2 };
    apply_tuple(three); // THREE

    return 0;
}

EDIT: In case someone wants the solution to the problem https://wandbox.org/permlink/XkUjfypAMepJRPgZ

Upvotes: 1

Views: 85

Answers (1)

xskxzr
xskxzr

Reputation: 13040

The reason is that if the tuple argument is an lvalue, std::get returns an lvalue, even though the element is an rvalue reference. You can write your own my_get to resolve it:

// If the element is not an rvalue reference, behave the same as std::get
template< std::size_t I, class... Types >
constexpr std::enable_if_t <
              !std::is_rvalue_reference_v<std::tuple_element_t<I, std::tuple<Types...>>>, 
               std::tuple_element_t<I, std::tuple<Types...>>const&
          >
    my_get( const std::tuple<Types...>& t ) noexcept
{
    return std::get<I>(t);
}

// If the element is an rvalue reference, move the result of std::get
template< std::size_t I, class... Types >
constexpr std::enable_if_t <
              std::is_rvalue_reference_v<std::tuple_element_t<I, std::tuple<Types...>>>, 
              std::tuple_element_t<I, std::tuple<Types...>>
          >
    my_get( const std::tuple<Types...>& t ) noexcept
{
    return std::move(std::get<I>(t));
}

Use my_get instead of std::get in your code, then everything goes well.

Upvotes: 1

Related Questions