This is motivated by an answer I gave a newbie user, where I suggested they use an std::variant
instead of a union.
With a union, you may have something like the following:
struct Box {
struct Item { float value; };
using Boxes = std::vector<Box>;
union Value {
Item item;
Boxes boxes;
};
Value contents;
std::string label;
};
(not exactly what the original question had, I'm taking some poetic license here.) and with a variant, the class might look like this:
struct Box {
struct Item { float value; };
using Boxes = std::vector<Box>;
std::variant<Item, Boxes> contents;
std::string label;
};
The thing is, that with the first variant, I can write
if (box.contents.boxes.size() > 2) { foo(); }
and provided that I've already established there are going to be sub-boxes, this will work.
With an std::variant
, I have to write:
if (std::get<Boxes>(box.contents).size() > 2) { foo(); }
I feel the second version is much less readable, a bit confusing, and quite distracting. Plus - I have to know the type of boxes
.
What can I do, in my code, to spare my users the need to make this kind of std::get()
calls, and make their lives more pleasant?