Everyone creates std::vector
from std::initializer_list
, but what about the other way around?
eg. if you use a std::initializer_list
Yes you can do this, but you don't want to do it, because how you have to do it is pretty silly.
First, determine what the max length of your list is. There must be a max length, because size_t
is not unbounded. Ideally find a better (smaller) one, like 10.
Second, write magic switch code that takes a run-time integer, and maps it to a compile time integer, and then invokes a template class or function with that compile time integer. Such code needs a max integer size -- use the max length above.
Now, magic switch the size of the vector into a compile time length.
Create a compile time sequence of integers, from 0
to length-1
. Unpack that sequence in a initializer_list
construction, each time invoking []
on the std::vector
. Call your function with that resulting initializer_list
.
The above is tricky and ridiculous and most compilers will blow up on it. There is one step I'm uncertain of the legality of -- is the construction of an initializer_list
a legal spot to do varardic argument unpacking?
Here is an example of a magic switch: Can I separate creation and usage locations of compile-time strategies?
Here is an example of the indices, or sequence, trick: Constructor arguments from tuple
This post should only be of theoretical interest, because practically this is a really silly way to solve this problem.
Doing it with an arbitrary iterable is harder, without doing n^2 work. But as the above is already ridiculous enough, and the arbitrary iterable version would be more ridiculous... (Maybe with a pack of lambdas -- getting it so that the arguments are evaluated in order could be tricky. Is there a sequence point between the evaluation of the various arguments to an initializer list?)