I'm working on a problem (it's essentially an encoding problem), where the encoded type can be one of the 3 types:
The first type is fully described by 2
int8_ts. I can usestd::pairto contain this or use a struct.The second type can be fully described by a boolean.
The third type can be described by an integral value that takes on values in
{0, 1, 2, 3}, so basically auint2_t(if that exists). I can use a struct to contain this.
The issue I am having is I need to store all instances of the encoded type in some sequential container (ideally a std::vector<T>), but I'm having some trouble figuring out how to do this in a clean way.
I think I can use std::variant to represent the 3 types, or define a custom struct, perhaps with a kind member attribute (along with the attributes necessary to represent the 3 types) that tells me which one of the 3 types is being represented in an instance of the struct. The former seems like it's going to involve a lot of "type checking" using std::variant methods, and the latter is a lot of wasted memory.
Are there other approaches that can work here?
You're right, the obvious solution is
std::variant.Besides
std::variant, it's also feasible to store astd::array<std::uint8_t>, 2>and just treat it as one of the three types when needed. Depending on your needs, you don't even need to store which "union member" is active then.You can obviously use a plain
unionofA,B, andCas well.