简体   繁体   English

折叠 std::initializer_list 的构造函数的参数列表与“正常”折叠

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

I learn C++17 from C++17 STL Cookbook by Jacek Galowicz and there is such an example about lambdas :我从 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 (The author writes that there should be reinterpret_cast used instead of C-like casting, but the question is about why is this casting used)?为什么这里使用std::initializer_list以及为什么使用这种void转换(作者写道应该使用reinterpret_cast而不是类似 C 的转换,但问题是为什么要使用这种转换)?

When I change the multicall and for_each functions to such:当我将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), ...);
}

Everything works as expected, I get the same results.一切都按预期进行,我得到了相同的结果。

It looks like for some reasons this part of the book operates C++14-way.由于某些原因,本书的这一部分似乎以 C++14 方式运行。 Trick with std::initializer_list was needed before fold expressions were introduced in C++17 to call emulate variadic call.在 C++17 中引入折叠表达式来调用模拟可变参数调用之前,需要使用std::initializer_list技巧。 In C++17 fold with comma operator is absolutely legit在 C++17 中用逗号运算符折叠是绝对合法的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM