注意
库使用
basic_formatting_ostream
流类型进行记录格式化,因此在自定义属性值格式时operator<<
必须使用basic_formatting_ostream
代替的规则std::ostream
。
但是,在整个文档中,我看到的只是operator <<
上的std::ostream
而不是示例代码中的basic_formatting_ostream
。例如,请参阅自定义类型severity_level
here的重载。
根据我的测试,std::ostream
和basic_formatting_ostream
上的重载都运行正常。所以,我想知道在一个而不是另一个上重载的优点是什么。
答案 0 :(得分:3)
仅operator << (std::ostream&, ...)
重载没有问题,因为formatting_ostream
有
template< typename CharT, typename TraitsT, typename AllocatorT, typename T >
inline basic_formatting_ostream< CharT, TraitsT, AllocatorT >&
operator<< (basic_formatting_ostream< CharT, TraitsT, AllocatorT >& strm, T const& value)
{
strm.stream() << value;
return strm;
}
其中stream()
返回std::ostream&
。如果您使用第一个arg operator <<
重载formatting_ostream
,那么只能使用boost::log
,如果您为std::ostream&
重载,那么这可以用于boost::log
和另一个输出。
从头文件引用:
* This stream wrapper is used by the library for log record formatting. It implements the standard string stream interface
* with a few differences:
*
* \li It does not derive from standard types <tt>std::basic_ostream</tt>, <tt>std::basic_ios</tt> and <tt>std::ios_base</tt>,
* although it tries to implement their interfaces closely. There are a few small differences, mostly regarding <tt>rdbuf</tt>
* and <tt>str</tt> signatures, as well as the supported insertion operator overloads. The actual wrapped stream can be accessed
* through the <tt>stream</tt> methods.
* \li By default, \c bool values are formatted using alphabetical representation rather than numeric.
* \li The stream supports writing strings of character types different from the stream character type. The stream will perform
* character code conversion as needed using the imbued locale.
* \li The stream operates on an external string object rather than on the embedded one. The string can be attached or detached
* from the stream dynamically.
*
* Although <tt>basic_formatting_ostream</tt> does not derive from <tt>std::basic_ostream</tt>, users are not required to add
* special overloads of \c operator<< for it since the stream will by default reuse the operators for <tt>std::basic_ostream</tt>.
* However, one can define special overloads of \c operator<< for <tt>basic_formatting_ostream</tt> if a certain type needs
* special formatting when output to log.
答案 1 :(得分:0)
如果您只重载operator<<(std::ostream)
,它将适用于每个流输出,包括basic_formatting_ostream
。如果只重载operator<<(basic_formatting_ostream)
,它只适用于输出到该类型的流。
但是,您可能希望重载,例如,如果要向日志提供不同或更多信息(例如对象的地址)。