I learn C++17 from C++17 STL Cookbook by Jacek Galowicz and there is such an example about 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)?
When I change the multicall
and for_each
functions to such:
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. Trick with std::initializer_list
was needed before fold expressions were introduced in C++17 to call emulate variadic call. In C++17 fold with comma operator is absolutely legit
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.