问题
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