std :: ostream作为可选(!)函数参数

Sti*_*ery 3 c++ cout optional-parameters ostream

我想声明一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

设置nullprt显然不起作用,但如何做到这一点?

Jar*_*d42 7

用指针,或 boost::optional

void print_function(std::string & str, 
               std::ostream & out = std::cout, 
               std::ostream* other = nullptr)
{
    out << str;
    if (other)
    {
        *other << str;
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

void print_function(std::string & str, 
               std::ostream & out = std::cout, 
               boost::optional<std::ostream&> other = boost::none)
{
    out << str;
    if (other)
    {
        *other << str;
    }
}
Run Code Online (Sandbox Code Playgroud)