gpt4 book ai didi

c++ - 压入和弹出 std::tuple 的第一个元素

转载 作者:太空狗 更新时间:2023-10-29 20:22:11 25 4
gpt4 key购买 nike

我正在用这种方式用可变数量的参数(和不同类型)在 C++ 中编写一个函数

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

我想做的,但我不知道怎么做,是从元组中压入和弹出元素,特别是第一个元素......类似

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

Demo

请注意,它非常基本,不处理引用元组或 const 限定类型的元组,但它可能就足够了。

关于c++ - 压入和弹出 std::tuple 的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39101454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com