Home > Back-end >  Variant of variants in C
Variant of variants in C

Time:09-17

I have the following variant

std::variant<Type1, Type2<subType1>> myVariant;

Type2 is a template class, there are 2 possible sub types subType1, and subType2 are possible. Is the following supported?

std::variant<Type1, Type2<std::variant<subType1,subType2>> myVariant;

If yes, how would get<index>(myVariant) work with the inner variant?

edit: fix typo

CodePudding user response:

Is the following supported?

Yes, but not in the way you think.

std::variant<Type1, Type2<std::variant<subType1, subType2>>> myVariant;

is the same thing as:

using SomeType = Type2<std::variant<subType1, subType2>>;
std::variant<Type1, SomeType> myVariant;

The fact that SomeType is templated changes nothing to how the variant works. So:

If yes, how would get(myVariant) work with the inner variant?

get<index>(myVariant) will return either a Type1 or a Type2<std::variant<subType1, subType2>>. The inner variant does not come into play in any way shape or form.

CodePudding user response:

The problem is that a std::variant is a new type and is distinct from all the types it can hold. Just like a good old union:

union int_or_double {
    int i;
    double d;
};

which is neither an int nor a double but a distinct type that can hold either an int value or a double value.

So here std::variant<Type1, Type2<std::variant<subType1,subType2>> myVariant; cannot only hold values of Type2<std::variant<subType1,subType2>> but neither Type2<subType1>, nor Type2<subType2> (and of course Type1...).

In real world programming, I think that std::variant<Type1, Type2<subType1>, Type2<subType2>> would be much simpler to use...

  • Related