tags:

views:

168

answers:

2

Is this possible?

I know that you can initialize structs using list syntax.

IE

struct Foo f = { a, b, c};
return f;

is a possible to do this in one line as you would be with classes and constructors?

Thanks

+10  A: 

Create a constructor for the struct (just like a class) and just do

return Foo(a,b,c);

Edit: just to clarify: structs in C++ are just like classes with the minor difference that their default access-permission is public (and not private like in a class). Therefore you can create a constructor very simply, like:

struct Foo {
  int a;
  Foo(int value) : a(value) {}
};
Amir Rachum
+8  A: 

If you want your struct to remain a POD, use a function that creates it:

Foo make_foo(int a, int b, int c) {
    Foo f = { a, b, c };
    return f;
}

Foo test() {
    return make_foo(1, 2, 3);
}

With C++0x uniform initialization removes the need for that function:

Foo test() {
    return Foo{1, 2, 3};
    // or just: 
    return {1, 2, 3};
}
Georg Fritzsche
In C++0x, you can even `return {1,2,3};`
Cubbi
@Cubbi: Right, good point - although i think i'll prefer the explicit version to avoid maintenance pitfalls when we'll start using the new features in production.
Georg Fritzsche
I think the latter might be quite convenient if the return type itself is complicated: `tuple<X, Y, Z> test() { return /*tuple<X, Y, Z>*/{x, y, z};}`. (I guess sometimes the result type could even be mind-bogglingly complicated, perhaps even determined with the help of `decltype` and such, in which case it might be nice not having to repeat the deduction again :) )
UncleBens
`#define INIT_STRUCT(name, ...) []()->name{name n = {__VA_ARGS__}; return n;}()` VC++2010 doesn't support uniform initialization yet, sadly, but I found this way to do in-line initialization using lambdas.
Gunslinger47
@UncleBens: Also a good point. I'm just worried about subtile misbehaviours when only changing the return type - though maybe i'm being overly paranoid :)
Georg Fritzsche
@Gunslinger: Why use macros when you could use just one more line or use (pseudo-)variadic templates to initialize arbritrary structures?
Georg Fritzsche
I don't have much experience with template programming. I wouldn't know how to program a generic version of your make_foo function while still having the object qualify for return value optimization.
Gunslinger47
@Gunslinger: While its technically NRVO (as your macro is), the basic idea is that you can get the same effect using variadic templates - [#1](http://pastebin.com/RqFzvLEB). With VC10 not supporting them this has to be unrolled - [#2](http://pastebin.com/CrpGvwD1) - possibly using a script to generate that repititive code once or using Boost.PP.
Georg Fritzsche