Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    return;
}

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
myTuple.pop_front()

//add addThis as the first element of the tuple thereby increasing its size by one
myTuple.push_front(addThis)

Is this possible?

like image 340
Emmet Avatar asked Sep 19 '25 02:09

Emmet


1 Answers

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>());
}

Demo

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

like image 67
Jarod42 Avatar answered Sep 20 '25 18:09

Jarod42