gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:39 26 4
gpt4 key购买 nike

Boost.Log documentation ,据说

Note

The library uses basic_formatting_ostream stream type for record formatting, so when customizing attribute value formatting rules the operator<< must use basic_formatting_ostream instead of std::ostream.

但是,在整个文档中,我所看到的只是重载 operator <<std::ostream而不是 basic_formatting_ostream在示例代码中。例如,查看自定义类型的重载 severity_level here .

根据我的测试,std::ostream 上的重载和 basic_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 <<第一个参数 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.

关于c++ - 在 Boost.Log 中正确重载运算符 <<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32902904/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com