Search code examples
c++constantsunions

Initializing aggregate unions


I've got a union :

union my_union 
{ short int Int16; float Float; };

I'd like to create :

const my_union u1 = ???;
const my_union u2 = ???;

and initialize their values to be of different types respectively : u1 -> int16 u2 -> float

How do I do that ? If the above is not possible, are there any workarounds?


Solution

  • union can have any number of constructors - this will work for any datatypes without constructor, so your example is well if exclude string (or make pointer to string)

    #include <string>
    using namespace std;
    union my_union 
    { 
        my_union(short i16):
            Int16(i16){}
        my_union(float f):
            Float(f){}
        my_union(const string *s):
            str(s){}
    
        short int Int16; float Float; const string *str;
    };
    
    int main()
    {
        const my_union u1 = (short)5;
        const my_union u2 = (float)7.;
        static const string refstr= "asdf";
        const my_union u3 = &refstr;
    }
    

    There is more complicated way to create class, that owns by union, class must have a selector (scalar or vector datatype used) - to correctly destroy string.