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

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Tue Apr 5 12:24:19 PDT 2016


On 05.04.2016 07:39, Timothee Cour via Digitalmars-d wrote:
> what's D's answer for C++11's uniform initialization [1] which allows DRY code?
>

If it's just about DRY, D is in quite good shape.

A fun(A a, int b) {
     alias i=typeof(return);
     if(b==1) return i(0,1);
     else if(b==2) return i(2,3);
     else return fun(i(3,4), 1);
}



> Could we have this:
> ----
> struct A{
>    int a;
>    int b;
> }
>
> A fun(A a, int b) {
>    if(b==1) return i{0,1};
>    else if(b==2) return i{2,3};
>    else return fun(i{3,4}, 1);
> }
> ----
>
> As for which syntax to use, that's an orthogonal question, but here I
> used i{} since {} (from C++11) is already used by delegates (with
> tuples also being discussed at some point, which didn't pan out bc
> someone mentioned it was ambiguous in some case; see my next email
> proposal below though [2])
>
> ----
> {} // delegate (existing syntax)
> q{...} // comment (existing syntax)
> i{...} // uniform intialization (proposed syntax)
> t{...} // tuple(a,b) (proposed syntax)
> T{...} // TypeTuple!(a,b) (proposed syntax)
> ----
>
> [1] http://programmers.stackexchange.com/questions/133688/is-c11-uniform-initialization-a-replacement-for-the-old-style-syntax
> [2] EMAIL:proposed syntax for tuple: t{} and TypeTuple: T{}
>

Well, the following is allowed:

struct A{
     int a;
     int b;
}

void main(){
     A x={1,2};
     A y={b:2,a:1};
     assert(x==y);
}

It would be funny if the syntax for such literals was different in 
initialization position and in other places. (Even more strange than the 
fact that now, the expression syntax for initialization differs from the 
usual expression syntax. {} is not always a delegate literal. E.g. auto 
x={}; actually fails to compile.)


More information about the Digitalmars-d mailing list