Initializing a temporary aggregated object using curly braces

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 cannot find the correct syntax for creating a 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 is to add a constructor to the Aggregate class, but suppose I don't have 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 to know if it is possible to achieve this goal using braces initialization.

+5
3

, , ++ 0x.

class Aggregate {
public:
    int x, y;
};

void frobnicate(const Aggregate& arg) {

}

int main() {
    frobnicate({1, 2});
    return 0;
}

GCC 4.4 -std=c++0x. , VS2010 CTP ( , ).

++ 98/++ 03 .

+8
+3

" , , , ".

. , , :

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 an irrelevant design solution.

+1
source

All Articles