在 std::initializer_list 的构造函数的参数列表中折叠与 "normal" 折叠

Folding in argument list of std::initializer_list's constructor vs "normal" folding

我从 Jacek Galowicz 的 C++17 STL Cookbook 学习了 C++17,并且有这样一个关于 lambdas 的例子:

template <typename... Ts> static auto multicall(Ts... functions)
{
    return [=](auto x) { (void)std::initializer_list<int>{((void)functions(x), 0)...}; };
}

template <typename F, typename... Ts> static auto for_each(F f, Ts... xs)
{
    (void)std::initializer_list<int>{((void)f(xs), 0)...};
}

static auto brace_print(char a, char b)
{
    return [=](auto x) { std::cout << a << x << b << ", "; };
}

int main()
{
    auto f(brace_print('(', ')'));
    auto g(brace_print('[', ']'));
    auto h(brace_print('{', '}'));
    auto nl([](auto) { std::cout << '\n'; });

    auto call_fgh(multicall(f, g, h, nl));

    for_each(call_fgh, 1, 2, 3, 4, 5);
}

Why is the std::initializer_list used here and why is this void casting used(作者写道,应该使用 reinterpret_cast 而不是 C-like casting,但问题是是关于为什么要使用这个铸件)?

当我将 multicallfor_each 函数更改为这样时:

template <typename... Ts> static auto multicall(Ts... functions)
{
    return [=](auto x) { (functions(x), ...); };
}

template <typename F, typename... Ts> static auto for_each(F f, Ts... xs)
{
    (f(xs), ...);
}

一切都按预期进行,我得到了相同的结果。

由于某些原因,本书的这一部分似乎以 C++14 方式运行。 在 C++17 中引入折叠表达式以调用模拟可变参数调用之前,需要使用 std::initializer_list 技巧。在 C++17 中,用逗号运算符折叠是绝对合法的