Search code examples
c++templatesvariant

Variant of variants in C++


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


Solution

  • 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...