How to set union in class initializer?

Given a class such as the one below and the given union, how does one initialize the union to the correct value?

What is being attempted here is to use two or more different types as one of the core data types for the class. Instead of using void*, given that the types are known ahead of time a union of the types that are going to be used is constructed. The problem is how to initialize the correct union member when the class is instantiated. The types are not polymorphic, so the usual inheritance model did not seem appropriate. Some naive attempts to initialize the correct union member led nowhere.

union Union {
   int n;
   char *sz;
};

class Class {
   public:
   Class( int n ): d( 1.0 ), u( n ) {}
   Class( char *sz ): d( 2.0 ), u( sz ) {}
   ....
   double d;
   Union u;
};

After scouring for a solution, an answer became obvious, and could possibly be a good solution for this repository of answers, so I include it below.

7
задан user7116 8 June 2011 в 16:30
поделиться