Reputation: 591
Say, I have
struct Foo
{
char a;
char b;
};
void bar(Foo foo);
What's the most succinct way to initialize a struct and pass it to the function? Ideally I would like to write something like
bar(Foo = {'a','b'});
What if Foo was a union?
UPD: My sincere apologies, the question was supposed to be in relation to C++03 only. Also, in this particular case, going away from POD is to be avoided (the code is for embedded system, ergo shorter bytecode is sought after). vonbrand, thanks for the C++11 answer.
Upvotes: 5
Views: 3200
Reputation: 11791
In C++ 11 you can write:
bar({'a', 'b'});
or:
bar(Foo{'a', 'b'});
(see Stroustup's C++11 FAQ).
g++-4.8.2 accepts this without complaints only if you give it -std=c++11
, clang++-3.3 gives an error unless -std=c++11
Upvotes: 5
Reputation: 8514
You could add a constructor to your struct. e.g.
struct Foo
{
Foo(char a, char b) : a(a), b(b) {}
char a;
char b;
};
Then you could call your function
bar(Foo('a', 'b'));
If it was a union, you could have different constructors for the different types of the union.
Upvotes: 1