www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Union literals? (D1.0)

reply Leandro Lucarella <llucax gmail.com> writes:
Is there union literals?

I have this (example):

struct A
{
	int x;
}

struct B
{
	char z;
}

struct C
{
	int y;
	union U
	{
		A a;
		static struct D
		{
			B b;
			uint domain;
		}
		D d;
	}
	U u;
}

Is there any way to initialize a C in one line (so it can be const)? Like:

const c = C(10, C.U.D(B('b'), 15));

But I get: Error: cannot implicitly convert expression (D((B('b')),15u))
           of type D to A.

Unions can only be initalized to its first member?



-- 
Leandro Lucarella (luca) | Blog colectivo: http://www.mazziblog.com.ar/blog/
----------------------------------------------------------------------------
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
----------------------------------------------------------------------------
Salvajes, de traje, me quieren enseƱar
Salvajes, de traje, me quieren educar
Feb 07 2008
parent "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Leandro Lucarella" <llucax gmail.com> wrote in message 
news:20080207212438.GB16062 burns.springfield.home...

 Is there any way to initialize a C in one line (so it can be const)? Like:

 const c = C(10, C.U.D(B('b'), 15));
Since it's const, you can use the oh-so-special struct initializer syntax: const C c = { y: 10, u: { d: { b: B('b'), domain: 15}}}; But this is getting a little ugly. I'm not sure if the struct you posted was stripped down from a larger struct, or if you're just unaware of the fact that D has anonymous structs and unions. C can be declared more simply as: struct C { int y; union { A a; struct { B b; uint domain; } } } And then initialized: const C c = { y: 10, b: B('b'), domain: 15 }; Also any instances of C you create, you no longer have to write "c.u.d.b" etc., just "c.b".
Feb 07 2008