简体   繁体   中英

How to check the “final” type of a union?

let's say I have a Union like this :

union checkUnion{
    std::string* str;
    bool someBool;
    int aNumber;
};

How can I check which of these 3 items has been chosen during the program? I want to do individual if-queries for each of the items.

eg: [Pseudo-Code]

if (checkUnion == string)
{
   //CODE
}

if (checkUnion == bool)
{
   //DIFFERENT CODE
}

You can't. You either need to know beforehand the initialized value, or add the union to some larger struct. See this other SO question .

Update:

Unions on C++ are just for compatibility with C code, and you'd rarely need them. Even if you are creating some fancy network protocol you'd use a tool like google-protobuf than a hand-crafted union. The original objective on unions was to overlap bytes on different fields or structures, to save as many bytes as possible on those data structures while retaining compiler support.

On C++ you'd beter create a class hierarchy, and each variant as a subclass of a base class. Internally you will also have a discriminator, the C++ vtable , but the discrimination is handled by the compiler. Which is better maintainable and less error prone than hand crafted unions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM