c++ - 如何在 C++ 中查找可变类型列表的所有组合

标签 c++ c++11 c++14 metaprogramming variadic-templates

我想编写一个 C++ 元函数,给定一个类型列表,没有重复的元素,生成所有可能的子列表,大小为 sizeof...(list) - 1

更新:我正在寻找元函数 find_all 的通用实现,定义如下。我现在的实现只是专门化(硬编码)最多包含 5 个元素的列表的结果,这显然根本不是通用的。

下面是一些简单的定义和例子:

给定一个存储类型列表的容器:

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

还有它的一个“实例”:

struct A{};
struct B{};
struct C{};

using ABC = type_list<A, B, C>::type;

并使用名为 find_all 的元函数:

using found_result = find_all<ABC>;

结果应该是:

using expected_result = type_list<
  type_list<A, B>,
  type_list<A, C>,
  type_list<B, C>
>;

static_assert(
  std::is_same<
    expected_result,
    found_result
  >::value, "");

如果结果子列表中的元素或子列表本身的顺序不同,则可以接受,前提是顺序是确定的。所以下面的结果也是有效的,例如:

using another_possible_expected_result = type_list<
  type_list<B, A>,
  type_list<B, C>
  type_list<C, A>,
>;

我使用的是 C++11(clang 6.0、Linux x86_64),但使用 C++14 就没问题。

如果有帮助,我也在使用 brigand 元编程库,它具有用于列表/集合处理的有用函数,但我也接受使用其他库的答案。

最佳答案

如果你愿意使用 C++14 和 Boost,我另一个答案中的算法可以很容易地用 Boost Hana 实现:

#include <utility>
#include <boost/hana.hpp>

namespace hana = boost::hana;

template <typename Tup>
constexpr auto penultimate_sized_sublists(Tup types)
{
    constexpr auto size = hana::size(types);
    // hana::range is unusable with hana::transform,
    // hence the conversion to a hana::tuple
    constexpr auto indices = hana::to_tuple(hana::make_range(hana::size_c<0>, size));

    return hana::transform(indices, [&](auto index) {
        return hana::remove_at(types, index);
    });
}

Demo on Godbolt

关于c++ - 如何在 C++ 中查找可变类型列表的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51199417/

相关文章:

c++ - 动态连续数组

c++ - 统计c++文本文件每一行的字数

c++ - eclipse C/C++ "Program file does not exist"

c++ - std::atomic 的默认值是多少?

c++ - 为什么 Foo({}) 调用 Foo(0) 而不是 Foo()?

c++ - 为什么这个模板示例代码没有编译?

c++ - 在 C++11 使用声明中是否允许/需要 "typename"?

c++11 - c++ 中的 vigenere 密码

c++ - leetcode 中的二叉树层序遍历

c++ - IF 内有两个语句的简写 If/Else 语句