C++初始化列表
我必须用 struct MHD_OptionItem
类型的元素填充 std::vector
。 这个结构有这样的实现:
struct MHD_OptionItem
{
enum MHD_OPTION option;
intptr_t value;
void *ptr_value;
};
我已经尝试过这种方式:
vector<struct MHD_OptionItem> iov;
if(...)
iov.push_back({ MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL });
if(...)
iov.push_back({ MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout });
[....]
但是g ++编译器,正如预期的那样,对我说:
警告:扩展初始化列表仅适用于-std = c ++ 0x或-std = gnu ++ 0x
我知道我可以初始化一个临时结构体,然后将其传递给向量,但在我看来,这种方法效率低下,而且不太优雅。
我无法更改插入构造函数的结构,因为这不是我的代码,而是包含的库。
有没有一种优雅的方法可以在不使用 c++0x 语法的情况下做到这一点?
I have to fill a std::vector
with elements of type struct MHD_OptionItem
.
This struct have this implementation:
struct MHD_OptionItem
{
enum MHD_OPTION option;
intptr_t value;
void *ptr_value;
};
I have tried this way:
vector<struct MHD_OptionItem> iov;
if(...)
iov.push_back({ MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL });
if(...)
iov.push_back({ MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout });
[....]
but the g++ compiler, as expected, says to me:
warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
I know that I can initialize a temporary struct and then pass it to the vector, but this method seems to me to be inefficient and not so elegant.
I can't change the struct inserting a constructor because this is not my code but a library included.
There is an elegant way to do this without using c++0x syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您无法更改 struct 或您想将其保留为 POD:
另一种解决方案:
Assuming you cannot change the
struct
or you want to leave it a POD:Another solution:
您必须为您的结构创建一个构造函数。
然后你可以这样初始化:
You have to create a constructor for your struct.
Then you can initialize this way:
引入一个构造函数和复制构造函数,
并使用它进行初始化怎么样,
是的,你正在引入一个临时的。但语法仍然很优雅
How about having a constructor and copy constructor introduced,
And using it for initialization,
Yes, you are introducing a temporary. But still the syntax remains elegant
也许您可以提供一个包含所有 3 个参数的构造函数,然后按如下方式创建它:
May be you can provide a constructor taking all the 3 parameters and then create it as follows: