Reputation: 161
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.
Upvotes: 7
Views: 6015
Reputation: 161
For any type that does not have a constructor, it turns out that you can initialized it in a union. This answer on union initializers gives a hint to the solution:
union Union {
int n;
char *sz;
Union( int n ): n( n ) {}
Union( char *sz ): sz( sz ) {}
};
Now it works as expected. Obvious, if you knew what to look for.
Edit: You can also note the type used in the union in your class constructor, typically with an int or the like.
Upvotes: 9