The following code compiles fine in g++
.
#include <iostream>
#include <string>
using namespace std;
struct thing
{
int a;
char b;
string name;
};
int main()
{
thing t =
{
a : 23,
b : 'e',
name : "Hello"
};
cout << t.a << endl;
cout << t.b << endl;
cout << t.name << endl;
return 0;
}
I know that the C99 equivalent { .a = 23, .b = 'e', .name = "Hello" }
is not supported in C++, but why is the above supported? Is it standardised? What is the name of this constructor idiom?
To put the above in perspective, if you have a system with a lot of immutable classes used for thread-safe messaging (all const
and public
members), then it is much easier to construct an instance of such a class using named members rather than writing a constructor and using positional arguments.