Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking variadic tuples in c++17

Is there anything better in c++17 (maybe C++2a) than the classic C++14 way to unpack variadic tuple with std::index_sequence?

Anything better than this:

template <typename ...I>
class MultiIterator
{
public:
    MultiIterator(I const& ...i)
        : i(i...)
    {}

    MultiIterator& operator ++()
    {
        increment(std::index_sequence_for<I...>{});
        return *this;
    }


private:
    template <std::size_t ...C>
    void increment(std::index_sequence<C...>)
    {
        std::ignore = std::make_tuple(++std::get<C>(i)...);
    }

    std::tuple<I...> i;
};

Like fold expression, structured-bindings? Any hint? I can accept answer why I cannot use these mentioned C++17 features here - but I prefer "solution.

like image 656
PiotrNycz Avatar asked Jan 26 '18 15:01

PiotrNycz


People also ask

What is the difference between tuple_CDR () and tuple_car ()?

std::tuple_cat () concatenates two tuples into one. But I recently needed a tuple_cdr () to remove the first item from the tuple, leaving me the rest. A tuple_car () would just do std::get (tuple) to get the first time, so nobody bothers to write one.

How to unpack a fixed size container in C++17?

Unpacking a fixed size container in C++ can be tedious, and require you to fiddle around with std::get or std::tie. But not anymore, thanks to the new structured bindings introduced in C++17.

How to use tuples in C++?

Tuples in C++. 1. get() :- get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element. 2. make_tuple() :- make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in tuple.

How to pass a tuple instead of a parameter pack?

But now you have a tuple instead of a parameter pack. Trick with std::index_sequence<> and a helper method lets you call a normal method (that takes normal parameters), passing a tuple that holds those parameter values: template <class... T_values>


1 Answers

Since C++14 we have generic lambdas, and since C++17 we have fold expressions and std::apply effectively hiding the usual unpack logic:

std::apply( [](auto&... i){ ((void)++i,...); }, some_tuple );

note: for your information, the (void) thing is just to avoid any custom comma operator to kick in... you never know :)

like image 62
Massimiliano Janes Avatar answered Oct 18 '22 02:10

Massimiliano Janes