Comment #0 by bearophile_hugs — 2011-11-25T17:01:51Z
After using several unions for a while in D, I think the syntax to initialize fields of unions is not handy enough. An idea from GNU-C:
import std.stdio;
union Foo { int i; double d; };
void main() {
int x;
double y;
Foo u = void;
auto u1 = cast(Foo)x;
writeln(typeof(u1).stringof);
auto u2 = cast(Foo)y; // Error: e2ir: cannot cast y of type double to type Foo
writeln(typeof(u2).stringof);
}
See:
http://gcc.gnu.org/onlinedocs/gcc/Cast-to-Union.html#Cast-to-Union
But I don't like that GNU-C idea, a problem with cast() is that it's not precise enough, if there are two fields like this, what is a good way to assign 's' or 'u' using a cast()?
union Foo { int s; uint u; };
So I'd like a more explicit syntax.
A solution using named arguments seems good:
union Foo { int s; uint u; };
void bar(Foo f) {}
void main() {
bar(Foo(u:5));
}
Comment #1 by timon.gehr — 2011-11-26T08:43:51Z
(In reply to comment #0)
>
> But I don't like that GNU-C idea, a problem with cast() is that it's not
> precise enough, if there are two fields like this, what is a good way to assign
> 's' or 'u' using a cast()?
>
> union Foo { int s; uint u; };
cast(Foo)cast(uint)exp
cast(Foo)cast(int)exp
You understand that both are assigned, regardless of which one you choose and ergo it is never a problem?
Comment #2 by verylonglogin.reg — 2013-09-30T07:30:34Z
Another option may be to extend "static initialization" syntax:
---
struct S { int i; double d; }
union U { int i; double d; }
void f(T)(T){}
void main()
{
S s = { d: 5 }; // OK
U u = { d: 5 }; // NG because of Issue 7727
// Original suggestion:
f(S( d: 5 )); // yes, let's not separate structs and unions
f(U( d: 5 ));
// Another option:
f(cast(S) { d: 5 });
f(cast(U) { d: 5 });
}
---
I'd like to require a `cast` even if the argument type is known.
And about original suggestion:
Having naming arguments in D (not only in this case) looks like a good idea allowing one another coding style.
Comment #3 by verylonglogin.reg — 2013-11-09T10:55:45Z
A report for e2ir ICE from original testcase: Issue 11485