gpt4 book ai didi

c++ - 如何从 std::tuple 中删除元素?

转载 作者:行者123 更新时间:2023-12-03 08:42:21 28 4
gpt4 key购买 nike

给定一个

struct A{}; struct B{}; struct C{};
std::tuple<A,B,C> tabc;

如何删除第二个元素 B从中得到tuple<A,C> ,比如

std::tuple<A,C> tac = drop<B>(tabc);

或相同

std::tuple<A,C> tac = drop<1>(tabc);

我假设这会产生一个带有元素拷贝的新类型。

最佳答案

这相当简单,可以使用元编程技术进行编码:

template<size_t drop, size_t ...ixs>
constexpr auto calc_drop_sequence_dropper(std::index_sequence<ixs...>)
{
return std::index_sequence<(ixs >= drop ? ixs + 1 : ixs)...>{};
}

//Creates a monotonically increasing sequence on the range [0, `count`), except
//that `drop` will not appear.
template<size_t count, size_t drop>
constexpr auto calc_drop_copy_sequence()
{
static_assert(count > 0, "You cannot pass an empty sequence.");
static_assert(drop < count, "The drop index must be less than the count.");
constexpr auto count_sequence = std::make_index_sequence<count - 1>();
return calc_drop_sequence_dropper<drop>(count_sequence);
}

template<typename Tuple, size_t ...ixs>
constexpr auto copy_move_tuple_by_sequence(Tuple &&tpl, std::index_sequence<ixs...>)
{
using TplType = std::remove_reference_t<Tuple>;

return std::tuple<std::tuple_element_t<ixs, TplType>...>(
std::get<ixs>(std::forward<Tuple>(tpl))...);
}

template<size_t drop, typename Tuple>
constexpr auto drop_tuple_element(Tuple &&tpl)
{
using TplType = std::remove_reference_t<Tuple>;

constexpr size_t tpl_size = std::tuple_size<TplType>::value;

constexpr auto copy_seq = calc_drop_copy_sequence<tpl_size, drop>();

return copy_move_tuple_by_sequence(std::forward<Tuple>(tpl), copy_seq);
}

主要函数是 drop_tuple_element,它执行您假设的 drop 函数的操作。当然,如果您要删除多个元素,您希望一次性删除它们,而不是单独删除它们。因此您需要修改代码。

关于c++ - 如何从 std::tuple 中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62365176/

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