rfmas3
rfmas3

Reputation: 103

Using a C++ union, when which member you want is unknown

Basically, I have to overload the << operator for my tokenType struct, which follows as (cannot be changed, I have to use it this way)

struct tokenType 
{
    int category  ;   // one of token categories defined above
    union 
    {
        int  operand ;
        char symbol ; // '+' , '-' , '*' , '/' , '^' , '='
    } ;
    int  precedence() const ;
}

My header for the overloading method is:

ostream & operator<< ( ostream & os , const tokenType & tk)

So, I need to print out the value in the struct tk, either an int or a char. How can I access what is contained within the union, when I don't know if the variable will be operand or symbol? Thanks.

Upvotes: 4

Views: 1791

Answers (4)

Ed Heal
Ed Heal

Reputation: 60017

The int category bit tells you how to interpret the union. Usually this is an enumerated type.

Either way you just use a switch statement (or perhaps as you only have two categorys an if then else would suffice.

Upvotes: 3

Wyzard
Wyzard

Reputation: 34573

Isn't that what the "category" number is supposed to indicate? This looks like a tagged union, where the category is the tag. It should tell you whether the token is an operand or a symbol, and you can use that to decide which field to access in the union.

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 994131

What you would need to do is look at the category member (which is not part of the union) to decide which of the union elements to use. Something like the following might be useful (I'm guessing at the category definitions, obviously):

switch (tk.category) {
    case catOperand:
        os << tk.operand;
        break;
    case catSymbol:
        os << tk.symbol;
        break;
}

Upvotes: 5

Jonathan Leffler
Jonathan Leffler

Reputation: 754650

Since your operator takes a (constant reference to a) tokenType, and the category member identifies which element of the union is currently valid, you have the information needed to print it accurately.

Upvotes: 2

Related Questions