简体   繁体   中英

Is it possible to programmatically construct a std::initializer_list?

I am wrapping a C++ fn of the form

foo(input, std::initializer_list<Option> options);

I need to construct a list of options from data in another format, and pass them into foo . I can't see a way of constructing a std::initializer_list programmatically – is this right? (It would make sense if one was forced to use a more standard container, but I would like to check before re-factoring.)

There is no way in standard C++. std::initializer_list is a language support type. It exists to make it possible for us to use a language construct (list initialization).

As such, it's only the implementation that can create them, and an implementation is only required to do so when doing list initialization. Your implementation may offer an extension that allows their creation, but that is unlikely to result in standard code.

void test() {
  double d1 = 1.1;
  double d2 = 2.2;
  double d3 = 3.3;
  std::initializer_list<int> init_list{ static_cast<int>(d1), static_cast<int>(d2), static_cast<int>(d3) };
}

So you can, but for fixed sized lists only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM