使用 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
这篇关于使用 std::ostream 打印可变参数包的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!