Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing temporary aggregate object using curly braces

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.

like image 255
chalup Avatar asked Oct 06 '09 12:10

chalup


3 Answers

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.

like image 147
Alex B Avatar answered Sep 28 '22 14:09

Alex B


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

like image 37
Alexey Malistov Avatar answered Sep 28 '22 16:09

Alexey Malistov


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

like image 34
Georg Fritzsche Avatar answered Sep 28 '22 15:09

Georg Fritzsche