views:

463

answers:

3

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.

+1  A: 

"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.

Georg Fritzsche
This however also changes the property of the type from being an Aggregate (and also a POD in this case) to a non aggregate. This may not be expected, and it would require a search and replace for all prior {} initialization.
Richard Corden
+7  A: 

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.

Alex B
+2  A: 

It is not possible now. Because of this the new standard C++ 0x introduced the concept of a Initializer lists and Uniform_initialization.

Alexey Malistov