Emmet Emmet - 1 year ago 82
C++ Question

Pushing and popping the first element of a std::tuple

I am writing a function in C++ with a variable number of arguments (and different types) in this way

template<typename ...Ts>
void myFunction(Ts ...args)
//create std::tuple to access and manipulate single elements of the pack
auto myTuple = std::make_tuple(args...);

//do stuff


What i would like to do, but I don't know how, is to push and pop elements from the tuple, in particular the first element... something like

//remove the first element of the tuple thereby decreasing its size by one

//add addThis as the first element of the tuple thereby increasing its size by one

Is this possible?

Answer Source

You may do something like

template <typename T, typename Tuple>
auto push_front(const T& t, const Tuple& tuple)
    return std::tuple_cat(std::make_tuple(t), tuple);

template <typename Tuple, std::size_t ... Is>
auto pop_front_impl(const Tuple& tuple, std::index_sequence<Is...>)
    return std::make_tuple(std::get<1 + Is>(tuple)...);

template <typename Tuple>
auto pop_front(const Tuple& tuple)
    return pop_front_impl(tuple,
                          std::make_index_sequence<std::tuple_size<Tuple>::value - 1>());


Note that it is really basic and doesn't handle tuple of reference, or tuple of const qualified type, but it might be sufficient.

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