I have objects of different types derived from a single super-type. I wonder if there are any disadvantages in using std::initializer
list in a range for loop like this:
for(auto object: std::initializer_list<Object *>{object1, object2, object3}) {
}
Is it completely OK and efficient or would it be better to use an array? To me the std::array
solution seems to be more restrictive for the compiler and there is a disadvantage of explicitly stating the size:
for(auto object: std::array<Object*, 3>{object1, object2, object3}) {
}
Is there any other or nicer way of iterating over an explicitly given list of objects?
You can simply write
There is no need to use the verbose
std::initializer_list
inside the loopLive Example.
If you want to do it on-the-fly without defining
px
andpy
, you can indeed usestd::initializer_list<B*>{ &x, &y }
inside the loop.