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

时间:2016-06-30 11:28:38

标签: 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;
    }
}

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

3 个答案:

答案 0 :(得分:7)

带指针的

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;
    }
}

答案 1 :(得分:1)

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

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

 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_streamstd::ostream nothing 。还有other ways来实现它。

希望有所帮助。

答案 2 :(得分:1)

我只是使用函数重载,而不是默认参数

// 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的语句需要与来自其他函数之一的语句交错),那么引入辅助函数以在单独的,更细粒度的部分中实现逻辑