Search code examples
c++variadic-templatesc++17structured-bindingsfold-expression

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.


Solution

  • 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 :)