BlueDespero
BlueDespero

Reputation: 3

Is there a way to populate C++ initializer_list with a for loop (or any other loop)?

I need to create an interactive session in C++ where user can test a class I created. That includes creating objects of that class with its different constructors. One of them is a collection constructor using initializer_list.

In my code I can run:

MyClass example = {1, 2, 3, 4};

Now I need to find the method to use it during interactive session. Somehow I need to fill the {} with the input provided by the user. User can pass up to 100 argments in that list, so I probably need some kind of a loop solution to my problem. Something working like (Sorry for C++/Python pseudocode mixture):

MyClass example = {a for a in user_input};

Do you know anything I can use to solve this?

Upvotes: 0

Views: 1483

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275405

std::initializer_list has a constexpr length. This means its length is always known at compile time. User input doesn't have this property.

So it isn't suitable to store user input.

A std::vector has a non-compile time length. Consider using it.

Have MyClass accept a std::span or a std::vector instead of or in addition to an initializer_list. (std::span is newer than ).

Then pass that in. There are a number of ways you can populate a std::vector with user input.

Upvotes: 0

Nicol Bolas
Nicol Bolas

Reputation: 473447

The source data for a std::initializer_list is always a braced-init-list: {/*stuff*/}. Only this grammatical construct can provide the backing array for this type.

initializer_list, as the name suggests, is for initializing something; it's just an intermediary. If you need to loop over some hand-generated list of items, this is what containers are for.

Upvotes: 2

Related Questions