For a class like below and this union, how to initialize the union of the correct value?
Here, attempts are made to use two or more different types as one of the main data types for a class. Instead of using void *, given that the types are known in advance, a union of the types to be used is built. The problem is how to initialize the correct member of the union when instantiating the class. Types are not polymorphic, so the usual inheritance model seems inappropriate. Some naive attempts to initialize the correct union member have failed.
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 cleaning up for the solution, the answer became obvious and might be a good solution for this answer repository, so I included it below.
glenng
source share