Home > Back-end >  How to expand the initializer list parameters pack?
How to expand the initializer list parameters pack?

Time:02-22

Codes like:

template <typename... type>
void print(type... pack) {
    ((std::cout << pack << " "), ...);
}

But I have parameters like: { {1, 2, 3}, {4, 5, 6} }

So how can I pass this to the function ? Or, how to expand the parameters pack like this ?

CodePudding user response:

I suppose you want to expand all the initlizer_list in a row.

// for single initializer_list
template <typename T>
void print(std::initializer_list<T> args) {
    for (const auto arg : args) {
        std::cout << arg << " ";
    }
}

// for nested initializer_list
template <typename T>
void print(std::initializer_list<std::initializer_list<T>> args) {
    for (const auto arg : args) {
        print(arg);
    }
}

See demo

CodePudding user response:

But I have parameters like: { {1, 2, 3}, {4, 5, 6} }

You can pack them into std::tuples

#include<iostream>
#include<tuple>

template <typename... Tuples>
void print_tuples(Tuples... tuples) {
  (std::apply([](auto... args) {
    ((std::cout << args << " "), ...);
  }, tuples), ...);
}

Then

print_tuples(std::tuple{1, 2, 3}, std::tuple{4, 5, 6});

Demo

  • Related