我从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);
}
为什么在这里使用std::initializer_list
以及为什么使用这种void
铸造(作者写道应该使用reinterpret_cast
代替C-like铸造,但问题是为什么使用这种铸件)?
当我将multicall
和for_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-way。在C ++ 17中引入折叠表达式以调用模拟可变参数调用之前,需要使用std::initializer_list
。在C ++中,使用逗号运算符17折是绝对合法的