我从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而不是类似C的转换,但是问题是为什么要使用这种转换)?
当我将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方式。std::initializer_list
在C ++ 17中引入折叠表达式以调用模拟可变参数调用之前,需要使用技巧。在C ++ 17中使用逗号运算符折叠绝对合法
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句