Let's say I have a class:
class Aggregate {
public:
int x;
int y;
};
I know how to initialize an object using curly braces:
Aggregate a1 = { 1500, 2900 };
But I can't find a proper syntax to create temporary object and pass it as an argument to some method, for example:
void frobnicate(const Aggregate& arg) {
// do something
}
//...
frobnicate(Aggregate {1500, 2900}); // what should this line look like?
The easiest way would be to add the constructor to Aggregate class, but let's assume I don't have an access to the Aggregate header. Another idea would be to write some kind of factory method, i.e.
Aggregate makeAggregate(int x, int y).
I can also create an object and then pass it as an argument, etc. etc.
There are many solutions, but I'm just curious if it's possible to achieve this goal using curly braces initialization.
What you want is possible with C++0x initializer lists.
class Aggregate {
public:
int x, y;
};
void frobnicate(const Aggregate& arg) {
}
int main() {
frobnicate({1, 2});
return 0;
}
GCC 4.4 already supports this with -std=c++0x
flag. Possibly VS2010 CTP supports this too (correct me if I'm wrong).
With C++98/C++03 you will have to write and invoke a constructor.
It is not possible now. Because of this the new standard C++ 0x introduced the concept of a Initializer lists and Uniform_initialization.
"There are many solutions, but I'm just curious if it's possible to achieve this goal using curly braces initialization."
Not possible. If you can't change the source then your only options are to wrap that in an inline function or a helper struct:
struct AggregateHelper
{
Aggregate a;
AggregateHelper(int x, int y) { a.x=x; a.y=y; }
operator const Aggregate& () { return a; }
};
frobnicate(AggregateHelper(1500,2900));
edit: removed irrelevant constructor solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With