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

Time:03-30

Some code will help making sense:

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

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

Instead of having MySuperType being a std::variant of another std::variant and a std::vector of std::variant, I would like to have all types unpacked into a single std::variant deriving from MyType.

So the expected result in that case would be (written manually):

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

Is it possible? How can I achieve this?

CodePudding user response:

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

Template partial specialization should be enough

#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

  • Related