...

/

Heterogenous Collections Using Variant

Heterogenous Collections Using Variant

Learn how to use variants for heterogenous collections and access values using the std::get() function.

Variant use in heterogenous collections

Now that we have a variant that can store any provided list, we can expand this to a heterogeneous collection. We do this by simply creating a std::vector of our variant:

Press + to interact
using VariantType = std::variant<int, std::string, bool>;
auto container = std::vector<VariantType>{};

We can now push elements of different types to our vector:

Press + to interact
container.push_back(false);
container.push_back("I am a string");
container.push_back("I am also a string");
container.push_back(13);

The vector will now look like this in memory, where every element in the vector contains the size of the variant, which in this case is sizeof(std::size_t) + sizeof(std::string):

Press + to interact
Vector of variants
Vector of variants

Of course, we can also pop_back() or modify the container in any other way the container allows:

Press + to interact
container.pop_back();
std::reverse(container.begin(), container.end());
// etc...

Accessing the values in our variant container

Now that we have the ...