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

南楼画角 提交于 2019-12-24 00:38:27

问题


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.)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/52183608/is-it-possible-to-programmatically-construct-a-stdinitializer-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!