jeudi 5 juillet 2018

How to find all combinations of variadic typelist in C++

I would like to write a C++ metafunction that given a list of types, with no duplicated elements, generate all the possible sublists with size sizeof...(list) - 1.

Below some simple definitions and an example:

Given a container that stores a list of types:

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

And an "instance" of it:

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

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

And using the metafunction, called find_all:

using found_result = find_all<ABC>;

The result should be:

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, "");

It's acceptable if the elements in the resulting sublists or the sublists themselves are in a different order provided that the ordering is deterministic. So the following result is also valid, for instance:

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

I am using C++11 (clang 6.0, Linux x86_64), but it would be ok using C++14.

If it helps, I am also using the brigand metaprogramming library, which has useful functions for list/set handling, but I accept answers that use other libraries as well.

Aucun commentaire:

Enregistrer un commentaire