在Boost.Log中正确重载运算符<<

Lingxi

Boost.Log文档中,据说

注意

该库使用basic_formatting_ostream流类型进行记录格式化,因此自定义属性值格式设置规则时,operator<<必须使用basic_formatting_ostream而不是std::ostream

然而,在整个文件中,所有我看到的是超载operator <<std::ostream,而不是basic_formatting_ostream在示例代码。例如,在severity_level 此处查看自定义类型的重载

根据我的测试,在过载std::ostreambasic_formatting_ostream两个正常工作。因此,我想知道在一个而不是另一个上重载的优点是什么。

永远

还有,在短短超载没有问题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 <<使用first arg重载,则此参数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.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章