Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Is it possible? How can I achieve this?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading