【问题标题】:std::ostream as optional (!) function parameterstd::ostream 作为可选 (!) 函数参数
【发布时间】: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显然是不行的,但是怎么办呢?

【问题讨论】:

标签: c++ cout optional-parameters ostream


【解决方案1】:

带指针,或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 方法...或者至少在指针方法之前。
  • @Nawaz: 有些人不希望依赖提升 :-( 。所以直到optional 在 ``std::`...
  • 我上次检查时从标准中排除的可选引用。
  • 或来自 C++17 的 std::optional :)
【解决方案2】:

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

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

【讨论】:

  • 这可能是最简单直接的解决方案,也不需要boost。
【解决方案3】:

您可以使用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,它什么都不做。还有other ways也可以实现。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2015-03-02
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    相关资源
    最近更新 更多