将variant的container拆包成container的variant,结合内部的variant类型

Unpacking a container of variant into a variant of containers, combined with the inner variant types

一些代码有助于理解:

#include <variant>
#include <vector>
#include <string>

using MyType = std::variant<int, float, string>;
using ContainerOfMyType = std::vector<MyType>;
using MySuperType = std::variant<MyType, ContainerOfMyType>;

我不想让 MySuperType 成为另一个 std::variantstd::variantstd::variantstd::vector,而是将所有类型解压到来自 MyType.

的单个 std::variant

所以这种情况下的预期结果将是(手动编写):

using MySuperType = std::variant<int, float, string, 
                                 std::vector<int>, std::vector<float>,
                                 std::vector<string>>;

可能吗?我怎样才能做到这一点?

I would like to declare a new variant type that contains all these base types, plus vector of each of these base types.

模板部分专业化应该足够了

#include <variant>
#include <vector>

template<class Var>
struct MySuper;

template<class... Args>
struct MySuper<std::variant<Args...>> {
  using type = std::variant<Args..., std::vector<Args>...>;
};

Demo

对于 Boost.Mp11,这是一个简短的 one-liner(一如既往):

using MySuperType = mp_append<MyType, mp_transform<std::vector, MyType>>;

mp_transform<vector, MyType> 为您提供每种类型的 vectorvariant,然后 mp_append 将这两个连接在一起。

Demo.