Reputation: 3
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
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 c++11).
Then pass that in. There are a number of ways you can populate a std::vector
with user input.
Upvotes: 0
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