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

std::ostream as optional (!) function parameter

我想声明一个默认写入 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显然不行,但是怎么办呢?

带指针,或boost::optional

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

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

您可以使用boost::optional或指针,如。但是,这两种方法都强制您在函数体中使用条件语句。

这是另一种方法,其优点是函数体的简单性:

 void print_function(std::string & str, 
              std::ostream & out = std::cout, 
              std::ostream& other = null_stream)
{
     out << str;
     other << str;  //no "if" required here.
 }

下面是您可以如何定义 null_stream 对象:

#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/null.hpp>

boost::iostreams::stream<boost::iostreams::null_sink> null_stream {
          boost::iostreams::null_sink{} 
};

这里 null_stream 是一个 std::ostream,它 什么都不做 。还有 other ways 来实现它。

希望对您有所帮助。

我会简单地使用函数重载,而不是默认参数

// declare the functions in a header

void print_function(std::string &str);
void print_function(std::string &str, std::ostream &ostr);
void print_function(std::string &str, std::ostream &ostr, std::ostream &other);

// and in some compilation unit, define them

#include "the_header"

void print_function(std::string &str)
{
       print_function(str, std::cout);
}

void print_function(std::string &str, std::ostream &ostr)
{
     // whatever
}

void print_function(std::string & str, 
                    std::ostream &ostr, 
                    std::ostream &other)
{
    print_function(str, ostr);

    other << str;
}

这些函数的所有三个版本都可以做任何你喜欢的事情。根据您的需要,任何一个都可以使用其他的来实现。

如果您需要在三个函数中交错逻辑(例如,影响 other 的语句需要与来自其他函数之一的语句交错),那么引入辅助函数以单独、更细粒度地实现逻辑, 零件.