January 2018
Intermediate to advanced
374 pages
9h 53m
English
Now that we have a variant which can store any type of a provided list, we can expand upon this to a heterogeneous container. We do this by simply creating a std::vector of our variant.
using VariantType = std::variant<int, std::string, bool>;
auto container = std::vector<VariantType>{};
We can now push elements of different types to our vector:
container.push_back(false);
container.push_back(std::string{"I am a string"});
container.push_back(std::string{"I am also a string"});
container.push_back(13);
The vector will now look like this in memory, where every element in the vector has the size of the variant, in this case sizeof(std::string):
Of course, we can also pop_back(), or modify ...