c++ - 如何在 C++ 中创建类型列表的 n 路笛卡尔积?

标签 c++ templates c++17 variadic-templates

不言自明。

基本上,假设我有这样的类型列表:

using type_list_1 = type_list<int, somestructA>;
using type_list_2 = type_list<somestructB>;
using type_list_3 = type_list<double, short>;

它们可以是类型列表的可变数量。

如何获取笛卡尔积的类型列表?

result = type_list<
type_list<int, somestructB, double>,
type_list<int, somestructB, short>,
type_list<somestructA, somestructB, double>,
type_list<somestructA, somestructB, short>
>;

我确实涉足了如何创建双向笛卡尔积,如下所示: How to create the Cartesian product of a type list? ,但n方式似乎并不那么微不足道。

现在我正在努力...

template <typename...> struct type_list{};

// To concatenate
template <typename... Ts, typename... Us>
constexpr auto operator|(type_list<Ts...>, type_list<Us...>) {
   return type_list{Ts{}..., Us{}...};
}

template <typename T, typename... Ts, typename... Us>
constexpr auto cross_product_two(type_list<T, Ts...>, type_list<Us...>) {
    return (type_list<type_list<T,Us>...>{} | ... | type_list<type_list<Ts, Us>...>{});
}

template <typename T, typename U, typename... Ts>
constexpr auto cross_product_impl() {
    if constexpr(sizeof...(Ts) >0) {
        return cross_product_impl<decltype(cross_product_two(T{}, U{})), Ts...>();
    } else {
        return cross_product_two(T{}, U{});
    }
}

我只想说,考虑到正确执行它是多么困难,只需使用巴里的答案中的升压即可。不幸的是,我必须坚持使用手动方法,因为要使用升压与否是来自其他地方的决定:(

最佳答案

Boost.Mp11 ,这是一句简短的话(一如既往):

using result = mp_product<
    type_list,
    type_list_1, type_list_2, type_list_3>;

Demo .

关于c++ - 如何在 C++ 中创建类型列表的 n 路笛卡尔积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59409722/

相关文章:

c++ - Rand() % 14 仅生成值 6 或 13

c++ - 展平一组类型,其中非类型值是展平的一部分

python - 从 .txt 文件加载页面内容会破坏 Django 模板系统

c++ - c++17中的非类型模板参数可以是decltype(auto)吗?

c++ - 简历限定符和右值引用

C++17 复制构造函数,std::unordered_map 上的深度复制

c++ - 为什么可以在 C++ 中的长度为 0 的数组中添加定义元素

c++ - 带有通配符的 ifstream

c++ - 如何在 codelite 中运行多个程序

用于评估指向成员的指针的 C++ 可变参数模板