使用 std::ostream 打印可变参数包的最简单方法是什么?
使用 std::ostream
打印以逗号分隔的参数包的最简单方法是什么?
What is the easiest way to print a parameter pack, separated by commas, using std::ostream
?
示例:
template<typename... Args>
void doPrint(std::ostream& out, Args... args){
out << args...; // WRONG! What to write here?
}
// Usage:
int main(){
doPrint(std::cout,34,"bla",15); // Should print: 34,bla,15
}
注意:可以假设 <<
运算符的相应重载可用于所有类型的参数包.
Note:
It may be assumed that a corresponding overload of the <<
operator is available for all types of the parameter pack.
推荐答案
无需递归调用和您想要的逗号.
Without recursive calls and commas where you wanted.
在c++11/c++14通过参数包扩展:
template <typename Arg, typename... Args>
void doPrint(std::ostream& out, Arg&& arg, Args&&... args)
{
out << std::forward<Arg>(arg);
using expander = int[];
(void)expander{0, (void(out << ',' << std::forward<Args>(args)), 0)...};
}
演示
在c++17 使用折叠表达式:
template <typename Arg, typename... Args>
void doPrint(std::ostream& out, Arg&& arg, Args&&... args)
{
out << std::forward<Arg>(arg);
((out << ',' << std::forward<Args>(args)), ...);
}
演示 2
相关文章