C ++ Initializer Lists

I have to fill std::vector elements of type struct MHD_OptionItem . This structure has the following implementation:

 struct MHD_OptionItem { enum MHD_OPTION option; intptr_t value; void *ptr_value; }; 

I 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, tells me:

warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x

I know that I can initialize a temporary structure and then pass it to a vector, but this method seems inefficient and not very elegant to me.

I cannot change the construction that inserts the constructor, because this is not my code, but a library.

Is there an elegant way to do this without using C ++ 0x syntax?

+4
source share
4 answers

Assuming you cannot modify the struct or want to leave it a POD:

 void f() { struct { MHD_OptionItem operator ()(enum MHD_OPTION opt, intptr_t val, void *ptr = 0) { MHD_OptionItem x = {opt, val, ptr}; return x; } } gen; vector<struct MHD_OptionItem> iov; if(...) iov.push_back(gen(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL)); if(...) iov.push_back(gen(MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout)); [....] } 

Another solution:

  struct Gen : MHD_OptionItem { Gen(enum MHD_OPTION opt, intptr_t val, void *ptr = 0) { option = opt; value = val; ptr_value ptr; } }; vector<struct MHD_OptionItem> iov; if(...) iov.push_back(Gen(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL)); if(...) iov.push_back(Gen(MHD_OPTION_CONNECTION_TIMEOUT, connectionTimeout)); [....] 
+6
source

You need to create a constructor for your structure.

 struct MHD_OptionItem { MHD_OptionItem(enum MHD_OPTION _option, intptr_t _value, void *_ptr_value) : option(_option), value(_value), ptr_value(_ptr_value) {} enum MHD_OPTION option; intptr_t value; void *ptr_value; }; 

Then you can initialize this path:

 ov.push_back(MHD_OptionItem(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL)); 
0
source

How to create a copy constructor and constructor,

 struct MHD_OptionItem { //... MHD_OptionItem(MHD_OPTION, intptr_t, void*); // makes struct a non-POD MHD_OptionItem(const MHD_OptionItem&) // copy constructor }; 

And using it to initialize,

 iov.push_back(MHD_OptionItem(MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL)); 

Yes, you enter the temporary. But still the syntax remains elegant

0
source

Maybe you can provide the designer with all three parameters, and then create it like this:

 iov.push_back(MHD_OptionItem( MHD_OPTION_NOTIFY_COMPLETED, requestCompleted, NULL)); 
0
source

All Articles