5

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

3
  • 3
    When you say "programatically", do you mean "of a runtime-defined length"? Commented Sep 5, 2018 at 11:17
  • Not clear what is the problem. std::initializer_list<int> list{1,2,3}; what did you try? Commented Sep 5, 2018 at 11:18
  • @RichardHodges Yes. Sorry I didn't make that clear. I'm actually wrapping the C++ function for Java. Commented Sep 5, 2018 at 12:17

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Do tell more stories.
@SombreroChicken - I'm thinking of changing my user handle. Whenever someone leaves such a comment, I can't tell if they like what I wrote, or are telling me I'm misleading people.
Haha. I quite like your handle, I was just messing around as usual. I like what you wrote, don't worry. When are you writing a novel? That'd truly be about stories. Not just answers.
@SombreroChicken - Probably when I'll be done with this software development side gig :P
You certainly can instantiate your own std::initializer_list (and populate it, ironically, by list-initialization) but it's not particularly useful.
|
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.