[英]Brace enclosed initializer lists
I'm trying to pass in an array of Data*
pointers to a function. 我正在尝试将一个
Data*
指针数组传递给一个函数。
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? 有没有办法让数组实例化内联,并且可以在没有C ++ 0x的情况下执行此操作吗? Thanks in advance.
提前致谢。
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 http://www.cprogramming.com/tutorial/lesson17.html
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. 如果您特别需要传递对,那么请考虑使用
std::pair
。 These can be created inline using std::make_pair
. 这些可以使用
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. 但最后,使用STL容器或在调用函数之前声明数组变量可能更容易,因此您可以使用聚合初始化。 Or add the
-std=c++0x
flag. 或者添加
-std=c++0x
标志。
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): 如果你真的想要它没有C ++ 11的功能,你可能会尝试这样做(不是很好的代码,只是为了表明这个想法):
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.