www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Struct literals limitation

reply Jack Applegame <japplegame gmail.com> writes:
Why doesn't it compile?
 auto foo() {
     struct Foo {
         int a, b;
     }
     return Foo({
         a: 10,
         b: 20
     });
 }
Valid C++14:
 auto foo() {
     struct Foo {
         int a, b;
     };
     return Foo({
         .a = 10,
         .b = 20
     });
 }
Nov 16 2020
next sibling parent Dennis <dkorpel gmail.com> writes:
On Monday, 16 November 2020 at 10:22:49 UTC, Jack Applegame wrote:
 Why doesn't it compile?
 auto foo() {
     struct Foo {
         int a, b;
     }
     return Foo({
         a: 10,
         b: 20
     });
 }
Because in-place struct initialization has never been implemented. Once the named parameters DIP is implemented, you should be able to do that by removing the {}: https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1030.md
Nov 16 2020
prev sibling next sibling parent Atila Neves <atila.neves gmail.com> writes:
On Monday, 16 November 2020 at 10:22:49 UTC, Jack Applegame wrote:
 Valid C++14:
 auto foo() {
     struct Foo {
         int a, b;
     };
     return Foo({
         .a = 10,
         .b = 20
     });
 }
Nope: /tmp % clang++ -c -std=c++14 -pedantic cpp.cpp 1 :( cpp.cpp:6:13: warning: designated initializers are a C++20 extension [-Wc++20-designator] .a = 10, ^ 1 warning generated.
Nov 16 2020
prev sibling parent JN <666total wp.pl> writes:
On Monday, 16 November 2020 at 10:22:49 UTC, Jack Applegame wrote:
 Why doesn't it compile?
 auto foo() {
     struct Foo {
         int a, b;
     }
     return Foo({
         a: 10,
         b: 20
     });
 }
Valid C++14:
 auto foo() {
     struct Foo {
         int a, b;
     };
     return Foo({
         .a = 10,
         .b = 20
     });
 }
Foo foo = { a: 10, b: 20 } is working in D at the moment. I can't wait for better initialization, named arguments to come into play too. It's a shame that in some cases C is more expressive than D: https://github.com/gfx-rs/wgpu-native/blob/master/examples/triangle/main.c , it even allows to return a pointer to a struct literal.
Nov 17 2020