Convenient C++ struct initialisation
Solution 1:
Since style A
is not allowed in C++ and you don't want style B
then how about using style BX
:
FooBar fb = { /*.foo=*/ 12, /*.bar=*/ 3.4 }; // :)
At least help at some extent.
Solution 2:
Designated initializes will be supported in c++2a, but you don't have to wait, because they are officialy supported by GCC, Clang and MSVC.
#include <iostream>
#include <filesystem>
struct hello_world {
const char* hello;
const char* world;
};
int main ()
{
hello_world hw = {
.hello = "hello, ",
.world = "world!"
};
std::cout << hw.hello << hw.world << std::endl;
return 0;
}
GCC Demo MSVC Demo
Update 20201
As @Code Doggo noted, anyone who is using Visual Studio 2019 will need to set /std:c++latest
for the "C++ Language Standard" field contained under Configuration Properties -> C/C++ -> Language
.
Solution 3:
You could use a lambda:
const FooBar fb = [&] {
FooBar fb;
fb.foo = 12;
fb.bar = 3.4;
return fb;
}();
More information on this idiom can be found on Herb Sutter's blog.