Adele Zaini
Adele Zaini

Reputation: 21

Accessing active union member

Is there a simple way to understand which union member is active?

An example:

union Read_Value{
 char ch;
 float number;
 string str;
}

Suppose a void function reads from an input file stream and initialise Read_Value on the base of the type of the variable read. Assuming I don't know how the function works, how can I understand which of the three member is active?

Upvotes: 1

Views: 895

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122298

A bare union cannot tell you which is the active element. You have to keep track of that yourself.


Since C++17 std::variant is the "modern union". It has a index() method that tells you which is the active index. Example from cppreference:

#include <variant>
#include <string>
#include <iostream>
int main()
{
    std::variant<int, std::string> v = "abc";
 
    std::cout << "v.index = " << v.index() << '\n';
 
    v = {}; 
 
    std::cout << "v.index = " << v.index() << '\n';
}

Possible output:

v.index = 1
v.index = 0

Upvotes: 5

Useless
Useless

Reputation: 67733

Is there a simple way to understand which union member is active?

In general, using a tagged (or discriminated) union. This means storing some metadata (tracking which member is active) alongside the raw union.

The modern solution is indeed std::variant, which does all this for you.

If you don't have C++17 support, don't have it in your standard library's experimental or tr extensions, and for some reason can't use the Boost.variant precursor ... you can still write an old-style tagged union yourself.

I wouldn't call it simple though, at least not to do well.

Upvotes: 2

Related Questions