How to set the union in the class initializer?

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.

+7
source share
1 answer

For any type that does not have a constructor, it turns out that you can initialize it in a union. This response to connection initializers gives a hint:

 union Union { int n; char *sz; Union( int n ): n( n ) {} Union( char *sz ): sz( sz ) {} }; 

Now it works as expected. Obviously, if you knew what to look for.

Edit: You can also mark the type used in combining in your class constructor, usually with int or the like.

+9
source

All Articles