tags:

views:

140

answers:

4

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?

+2  A: 

Unions cannot contain non-POD data types such as string, so your question is meaningless.

anon
OP modified, question still stands
Maciek
little correct: union can have any datatypes, that has not constructor or destructor.
Dewfy
also non-trivial assignment operator
anon
+1  A: 

Notwithstanding the ban on non-POD member data (as elaborated above) the Standard says:

at 8.5.1.15: When a union is initialized with a brace-enclosed initializer, the braces shall only contain an initializer for the first member of the union.

so

const my_union u1 = {1};

should work but this form cannot be used for the second (and subsequent) members.

LaszloG
So you have to pick how you want to initialize it and make that the first member.
Zan Lynx
+7  A: 

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.

Dewfy
Please do not use HTML tags to format your code - simply select the code with the mouse and type Ctrl-K.
anon
DRY (don't repeat yourself). "5" is already int and "7." is alredy float. You don't need those nasty C casts.
fnieto
then try to distinguish const my_union u1 = 0This causes unambiguity between pointer const string * and short.That is why for clearness only I've used explicit modifiers.
Dewfy
A: 

You can do it, as described in the flagged answer. Unions however are there to alias memory - why would you want to use it in this way?

nj