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;
}
}
我会简单地使用函数重载,而不是默认参数
// 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::optional
或指针,如@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_stream
是一个不做任何事情的std::ostream
。还有其他方法可以实现它。
希望对你有帮助。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类