【发布时间】:2016-11-02 11:19:22
【问题描述】:
我想声明一个默认写入std::out 的函数,但也可以选择启用写入另一个输出流(如果提供)。例如:
print_function(std::string & str,
std::ostream & out = std::cout,
std::ostream & other = nullptr) // <-- how to make it optional???
{
out << str;
if (other == something) // if optional 'other' argument is provided
{
other << str;
}
}
设置nullprt显然是不行的,但是怎么办呢?
【问题讨论】:
-
在我看来,有两个重载会更自然,一个有两个参数,一个有三个参数。
-
@Hurkyl: 或者保留一个有 2 个参数并传递一个“
tee_stream”。 -
有一个流吞下输入(如stackoverflow.com/questions/11826554/… 的接受答案)是一个糟糕的解决方案,在这里。
标签: c++ cout optional-parameters ostream