Convenient C++ struct initialisation
c++, initialization, struct
Solution
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 2021
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`.
Problem
I'm trying to find a convenient way to initialise 'pod' C++ structs. Now, consider the following struct: ``` struct FooBar { int foo; float bar; }; // just to make all examples work in C and C++: typedef struct FooBar FooBar; ``` If I want to conveniently initialise this in C (!), I could simply write: ``` /* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C ``` Note that I want to explicitly avoid the following notation, because it strikes me as being made to break my neck if I change anything in the struct in the future: ``` /* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style? ``` To achieve the same (or at least similar) in C++ as in the `/* A */` example, I would have to implement an annoying constructor: ``` FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {} // -> /* C */ FooBar fb(12, 3.4); ``` Which feels redundant and unnecessary. Also, it is pretty much as bad as the `/* B */` example, as it does not explicitly state which value goes to which member. So, my question is basically how I can achieve something similar to `/* A */` or better in C++? Alternatively, I would be okay with an explanation why I should not want to do this (i.e. why my mental paradigm is bad). EDIT By convenient, I mean also maintainable and non-redundant.