1

I would like to pass multiple, non-contiguous values from an array to a method. This is currently working:

double constexpr args[]{ 0, 1, 2, 3, 4 };
void example(std::initializer_list<double>);
example({ args[1], args[3], args[4] });

In order to simplify the call, I would instead prefer to provide the arguments without the need to repeat the args variable along with each index. The following is what I attempted (I know all the indexes at compile-time):

template<size_t... I, typename T, size_t S>
std::initializer_list<T> get(T const (&array)[S]) {
    return { array[I]... };
}

example(get<1, 3, 4>(args));

However, the above call to the example method is passing what appears to be uninitialized memory (I am populating a vector from the initializer_list, and it ends up containing junk values like 6.95278e-310). Can anyone see what is wrong with my implementation of the get method?

Jeff G
  • 4,470
  • 2
  • 41
  • 76
  • 1
    To fix this just return a `std::array` instead. – NathanOliver Dec 02 '19 at 22:25
  • That solution works in my case, since the items I am trying to pass are light. However, in the general case, it may be preferable to return an `std::array` and change the result to return `&array[I]...` to prevent copying each item. – Jeff G Dec 02 '19 at 22:50

0 Answers0