문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top