uniform initialization in D (as in C++11): i{...}

ZombineDev via Digitalmars-d digitalmars-d at puremagic.com
Tue Apr 5 09:04:21 PDT 2016


On Tuesday, 5 April 2016 at 14:57:14 UTC, Adam D. Ruppe wrote:
> On Tuesday, 5 April 2016 at 14:45:33 UTC, ZombineDev wrote:
>> Yeah, that's what I had in mind. new Object{}, int(3) -> 
>> int{3}, T() -> T{} (in generic code), and {42, "tuple"} where 
>> the type can be deduced.
>>
>> Unfortunately the (1, 2, 3) syntax is can't be used for tuples 
>> because it is ambiguous/looks bad in some
>
>
>
> If it is supposed to be uniform, why have the type name in one 
> place but not another?
>
> I really don't understand what the problem with 
> Whatever!(x,y,z) is.
>
> (other than the fact that Tuple sucks. structs are better in 
> every way. but it isn't because of syntax.)

I still don't understand what's not uniform. In most cases you 
would want to use the curly braces without the type:

auto {a, b} tuple = { add( {1, 2, 3}, {4, 5, 6} ), {7, 8, 9} };
assert (tuple == {{5, 7, 9}, {7, 8, 9}});
assert (a == {5, 7, 9} && b == {7, 8, 9});

// pattern-matching (note: no `static` in front)
if (is(a : {5, y, 9}))
{
     writefln("The tuple is: {5, %s, 9}", y);
     // The `y` identifier is valid until the end of the statement.
}

auto {x, y, z} = tuple[0];
assert (x == 5 && y == 7 && z == 9);

struct Point { double x, y, z; }
Point3 add(Point3 {ax, ay, az} a, Point3 {bx, by, bz} b)
{ return { ax + bx, ay + by, az + bz };

However in some places this is ambiguous:
struct S1 { float x, y, z; }
struct S2 { int x, y, z; }
struct S3 { int a, b, c;}
void foo(S1);
void foo(S2);
void foo(S3); // foo is overloaded

foo({a: 1, b: 2, c: 3}); // unambiguous
foo({x: 1, y: 2, z: 3}); // error: the function call is ambiguous:
// both foo(S1) and foo(S2) are callable with `{x:1, y:2, z:3}`.
// Prefix the tuple with a type to disambiguate.

foo(S1{x: 1, y: 2, z: 3}); // both
foo(S2{x: 1, y: 2, z: 3}); // are unambiguous.



More information about the Digitalmars-d mailing list