如何在C ++中创建类型列表的n路笛卡尔积? [英] How can I create a n way Cartesian product of type lists in C++?
问题描述
自我解释。
基本上,说我有这样的类型列表:
Basically, say I have type lists like so:
using type_list_1 = type_list<int, somestructA>;
using type_list_2 = type_list<somestructB>;
using type_list_3 = type_list<double, short>;
它们可以是各种类型的类型列表。
They can be variadic number of type lists.
如何获取笛卡尔积的类型列表?
How do I get a typelist of Cartesian product?
result = type_list<
type_list<int, somestructB, double>,
type_list<int, somestructB, short>,
type_list<somestructA, somestructB, double>,
type_list<somestructA, somestructB, short>
>;
我确实对如何创建双向笛卡尔积进行了涉猎,如下所示: <一个href = https://stackoverflow.com/questions/9122028/how-to-create-the-cartesian-product-of-a-type-list>如何创建类型列表的笛卡尔积? ,但n种方法似乎并不那么简单。
I did dabble on how to create a two-way Cartesian product as given here: How to create the Cartesian product of a type list?, but n way seems to be no so trivial.
现在我正在尝试...
For now I am trying...
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{});
}
}
我只想说考虑到正确实现它有多困难,只需按照Barry的答案使用boost。不幸的是,我不得不坚持手动滚动方法,因为是否使用boost是来自其他地方的决定:(
I will just say that considering how difficult it is to get it right, just use boost as in the answer by Barry. Unfortunately I have to be stuck with a hand rolled approach because to use boost or not is a decision that comes from somewhere else :(
推荐答案
使用 Boost.Mp11 ,这是一条短线(一如既往):
With Boost.Mp11, this is a short one-liner (as always):
using result = mp_product<
type_list,
type_list_1, type_list_2, type_list_3>;
演示。
这篇关于如何在C ++中创建类型列表的n路笛卡尔积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!