logoalt Hacker News

quietbritishjim • today at 1:45 PM • 1 reply • view on HN

C++'s version of this is more verbose but still sometimes worth it: make the caller instantiate the struct and initialise it as separate statements:

   FooParams fooParams;  // Gives sensible defaults to all members
   fooParams.x = 1;
   fooParams.y = "xyz";
   foo(fooParams);
It doesn't work so well if you want to move construct things because you need to move at least twice: once when moving the value into the member, then you need to move the whole struct to the function argument `foo(std::move(fooParams))`. If you want it to copy something but avoid unnecessary copying then it's even more annoying because you need to move to the function argument still which looks odd when your goal is to copy overall.

Replies

SuperV1234 • today at 1:56 PM

You can write `foo({.x = 1, .y = "xyz"});` in C++20.

https://gcc.godbolt.org/z/srz4P6nzM

➕ show 3 replies