gpt4 book ai didi

c++ - 过滤嵌套动态元组(dynamic tuple of tuples)

转载 作者:行者123 更新时间:2023-11-27 23:35:44 26 4
gpt4 key购买 nike

我有一种动态元组结构:

template <typename... Elems> //Should only be tuples
class DynamicTuple {
vector<byte> data; //All data is stored contiguously
vector<tuple<size_t,size_t>> element_table; //First element is offset into the data vector; second is which index of the parameter pack holds the stored type.
/* ... */
}

现在我希望能够过滤掉所有包含类型列表的元组。

template <typename... Ts>
vector<tuple<Ts&...>> filter() {
vector<tuple<Ts&...>> result;
for (auto it : element_table) {
auto [offset, type] = it;
// ???
}
}

这里我需要能够检查“Elems”参数包的第 N 个索引中的类型是否是一个包含“Ts”参数包中所有类型的元组。如果是这样,我想推回一个包含这些值的元组。

凭直觉,我想使用“type”值从“Elems”参数包中获取类型,并使用 has_type 结构,就像这个答案中的结构:https://stackoverflow.com/a/41171291/11463887像这样的东西:

((has_type<Ts, tuple_element<type, tuple<Elems...>>::type>&& ...))

但是这不起作用,因为“类型”不是编译时常量表达式。有办法解决这个问题吗?

最佳答案

随着 has_type你已经有了,你可以用同样的方式定义一个type_subset测试元组中是否包含所有类型:

template <typename Ts, typename Tuple>
struct type_subset;

template <typename... Ts, typename... Us>
struct type_subset<std::tuple<Ts...>, std::tuple<Us...>>
: std::conjunction<has_type<Ts, std::tuple<Us...>>...> {};

然后您可能想找到与您的 type 匹配的正确类型通过迭代参数包和相应的索引来索引:

size_t i = 0;
bool match = ((type == i++ && type_subset<std::tuple<Ts...>, Elems>::value) || ...);

确保重置 i0在每次执行折叠表达式之前。你可能想把整个东西放在一个 lambda 或函数中来分隔 i并在其他条件下重用它。


也许更好的表现是在编译时将可能的结果保存到一个数组中,然后在运行时对其进行索引:

constexpr static std::array matches{type_subset<std::tuple<Ts...>, Elems>::value...};
bool match = matches[type];

无论哪种情况,您都需要确保 type < sizeof...(Elems) .特别是在第二个变体中,否则你将有未定义的行为(如果你不使用 .at 而不是 [] )。

关于c++ - 过滤嵌套动态元组(dynamic tuple of tuples),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59352540/

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