Is it possible to put several objects together inside a union?

后端 未结 6 1938
无人及你
无人及你 2021-02-08 06:38

What if I have this:

union{
    vector intVec ;
    vector floatVec ;
    vector doubleVec ;
} ;

Of cours

6条回答
  •  星月不相逢
    2021-02-08 06:52

    Now C++ standard supports variant. Check https://en.cppreference.com/w/cpp/utility/variant.

    std::variant

    Defined in header

    template    
    class variant;
    

    (since C++17)

    The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or in the case of error - no value (this state is hard to achieve, see valueless_by_exception).

    As with unions, if a variant holds a value of some object type T, the object representation of T is allocated directly within the object representation of the variant itself. Variant is not allowed to allocate additional (dynamic) memory.

    A variant is not permitted to hold references, arrays, or the type void. Empty variants are also ill-formed (std::variant can be used instead).

    A variant is permitted to hold the same type more than once, and to hold differently cv-qualified versions of the same type.

    Consistent with the behavior of unions during aggregate initialization, a default-constructed variant holds a value of its first alternative, unless that alternative is not default-constructible (in which case the variant is not default-constructible either). The helper class std::monostate can be used to make such variants default-constructible.

提交回复
热议问题