C++17 折叠表达式的经典示例是打印所有参数:
template<typename ... Args>
void print(Args ... args)
{
(cout << ... << args);
}
例子:
print("Hello", 12, 234.3, complex<float>{12.3f, 32.8f});
输出:
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
和
(cout << ... << (" " << args));
error: invalid operands to binary expression
我明白为什么最后两个版本不起作用。 这个问题有没有更优雅的解决方案,使用折叠表达式?
最佳答案
更新: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), ...);
}
用法:
int main()
{
print("a", 1, 1000);
}
a
1
1000
(注意:这也会打印尾随换行符。)
解释:
[](const auto& x){ cout << x << "\n"; }
是给定x
的 lambda版画x
和'\n'
.[](const auto& x){ cout << x << "\n"; }(args)
立即用args
调用 lambda .([](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>)
关于c++ - 使用折叠表达式打印所有带有换行符的可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43070062/