C++17 折叠表达式的经典示例是打印所有参数:
template<typename ... Args>
void print(Args ... args)
{
(cout << ... << args);
}
Example:
print("Hello", 12, 234.3, complex<float>{12.3f, 32.8f});
Output:
Hello12234.3(12.3,32.8)
我想在我的输出中添加换行符。但是,我找不到一个好的方法来做到这一点,到目前为止我发现的最好的方法是:
template<typename ... Args>
void print(Args ... args)
{
(cout << ... << ((std::ostringstream{} << args << "\n").str()));
}
然而,这并不是零开销,因为它构建了一个临时的ostringstream
对于每个参数。
以下版本也不起作用:
(cout << ... << " " << args);
error: expression not permitted as operand of fold expression
And
(cout << ... << (" " << args));
error: invalid operands to binary expression
我明白为什么最后两个版本不起作用。
使用折叠表达式是否有更优雅的解决方案来解决这个问题?
Update: T.C.下面的评论提供了更好的解决方案:
template<typename ... Args>
void print(Args ... args)
{
((cout << args << '\n'), ...);
}
您可以使用折叠表达超过逗号运算符:
template<typename ... Args>
void print(Args ... args)
{
([](const auto& x){ cout << x << "\n"; }(args), ...);
}
Usage:
int main()
{
print("a", 1, 1000);
}
a
1
1000
(注意:这也会打印尾随换行符。)
解释:
[](const auto& x){ cout << x << "\n"; }
是一个 lambda 给定x
prints x
and '\n'
.
[](const auto& x){ cout << x << "\n"; }(args)
立即调用 lambdaargs
.
-
([](const auto& x){ cout << x << "\n"; }(args), ...)
是一个折叠表达式逗号运算符以下列方式扩展:
// (pseudocode)
[](const auto& x){ cout << x << "\n"; }(args<0>),
[](const auto& x){ cout << x << "\n"; }(args<1>),
[](const auto& x){ cout << x << "\n"; }(args<2>),
// ...
[](const auto& x){ cout << x << "\n"; }(args<N>)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)