本文介绍了推入并弹出std :: tuple的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用这种方式用可变数量的参数(和不同类型)用C ++编写一个函数
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)
可能吗?
推荐答案
您可以执行以下操作
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>());
}
请注意,它确实很基本,不处理引用元组或const限定类型的元组,但它可能足够。
Note that it is really basic and doesn't handle tuple of reference, or tuple of const qualified type, but it might be sufficient.
这篇关于推入并弹出std :: tuple的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!