2015-10-02 35 views
5

Boost.Log documentation,据说正确重载运算符<<在Boost.Log

注意

库使用basic_formatting_ostream流类型的记录格式,所以定制属性值格式 时规则operator<<必须使用basic_formatting_ostream而不是 std::ostream

然而,在整个文件中,所有我看到的是在示例代码超载对std::ostream而非basic_formatting_ostreamoperator <<。例如,请参阅自定义类型的过载severity_levelhere

根据我的测试,std::ostreambasic_formatting_ostream的过载都正常工作。所以,我想知道重载的好处是什么,而不是另一个。

+1

使用'std :: ostream'的好处应该是非常明显的:您也可以将它用于“普通”输出。 :) –

回答

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&。如果将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. 
+0

但插入'basic_formatting_ostream'似乎做比插入'std :: ostream'更多的工作。例如,查看'basic_formatting_ostream'为'const char *'提供的重载的'operator <<'。 – Lingxi

+0

@Lingxi nope,'basic_formatting_ostream'只是尽量接近'basic_ostream'的接口。 – ForEveR

+0

因此,Boost.Log文档只是过时或什么? – Lingxi

0

如果你只重载operator<<(std::ostream),它会为每一个流输出工作,包括对basic_formatting_ostream。如果您只重载operator<<(basic_formatting_ostream)它只会用于输出到该类型的流。例如,如果要为日志提供不同或更多的信息(如对象地址),则可能需要重载