C ++, Union vs Class Inheritance

I have a specific problem and am stuck which approach is better than the other:

An enumerated structure that defines the data in a member of an OR union Class group with inheritance

An example code is given below:

Union based structure

  typedef union TokenValue{
   bool bValue;
   long lvalue;
   double dvalue;
   std::string svalue;
   }

  class Token{
  public:
   TokenType type;
   TokenValue value;
   };

Class inheritance

class TokenBase{
public:
  TokenType type;
  };



class TokenNumber: public TokenBase{
public:
bool isInt;
long lvalue;
double dvalue;
};

class TokenString: public TokenBase{
 public:
  std::string svalue;
 };
+5
source share
4 answers

This type of design is known as a discriminated union or labeled union . You can use Google for the "C ++ discinated union" to see some examples and approaches to this type of design.

A C union ++. , union union. union , ++ 11 , POD ( no std::string).

, , , (, PrintTo). ( , , , PrintTo union, switch TokenType, -OO.)

A union - , , , (no vtable). - , .

, Boost.Variant ++- .

+3

Token , " ". ; , , . . , bool, ; .

+4

/: . . .

, , - , , , ...

, .

0

++. , , - , , . , , , int, . .

0
source

All Articles