Search code examples
c++operator-overloadingunionsostream

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.


Solution

  • 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;
    }