Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 245
rfmas3 Avatar asked Dec 09 '22 01:12

rfmas3


2 Answers

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;
}
like image 52
Greg Hewgill Avatar answered Jan 31 '23 04:01

Greg Hewgill


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.

like image 28
Wyzard Avatar answered Jan 31 '23 04:01

Wyzard