如何扩展初始化列表参数包?

How to expand the initializer list parameters pack?

代码如下:

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

但我有如下参数: { {1, 2, 3}, {4, 5, 6} }

那么如何将它传递给函数呢? 或者,如何像这样扩展参数包?

我想你想连续展开所有 initlizer_list

// 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);
    }
}

demo

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

您可以将它们打包成 std::tuples

#include<iostream>
#include<tuple>

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

然后

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

Demo