Reputation: 31
I'm trying to pass in an array of Data*
pointers to a function.
void f(int argc, Data** argv) {
...
}
// at this point, I have Data* x, Data* y initialized
f(2, {x, y});
Is there some way to get code like this to run, where the array definition is inline inside the function call? Right now, the error this returns is
closure3.cc:15:8: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
closure3.cc:15:16: error: cannot convert ‘<brace-enclosed initializer list>’ to ‘Data**’ for argument ‘2’ to ‘void f(int, Data**)’
Is there some way to get the array instantiated inline, and is it possible to do this without C++0x? Thanks in advance.
Upvotes: 0
Views: 4555
Reputation: 19347
The brace initializers are only available when declaring an array variable. So you can't do it this way.
Technically you could do it with a function (note: this is untested)
Data ** pair_of_data(Data * x, Data * y)
{
Data ** result = new Data*[2];
result[0] = x;
result[1] = y;
return result;
}
but that's ugly for a few reasons:
If you specifically need to pass pairs, then consider using std::pair
instead. These can be created inline using std::make_pair
.
In the end, though, it's probably easier just to use an STL container, or declare an array variable just before calling the function, so that you use aggregate initialization. Or add the -std=c++0x
flag.
Upvotes: 0
Reputation: 3356
If you really want it without C++11 features, you may try to do it so (not good sort of code, just to show the idea):
vector<int> InitList(int first, ...)
{
vector<int> arr;
int *p = &first;
while(*(p + 1))
{
arr.push_back(*p);
p++;
}
return arr;
}
int main()
{
F(2, InitList(1, 2, 3));
}
Upvotes: -2
Reputation: 41
You might want to consider using variable length arguments so you don't have to instantiate the list inline.
http://www.cprogramming.com/tutorial/lesson17.html
Upvotes: 4