Boost日志非常量位域编译错误(向后兼容性问题)

boost log non-const bitfield compilation error (backward compatibility issue)

本文关键字:兼容性 问题 错误 非常 日志 常量 位域 编译 Boost      更新时间:2023-10-16

我从http://www.boost.org/doc/libs/1_61_0/libs/log/example/doc/tutorial_trivial_flt.cpp获取示例,并添加了位域打印:

#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
namespace logging = boost::log;
//[ example_tutorial_trivial_with_filtering
void init()
{
    logging::core::get()->set_filter
    (
        logging::trivial::severity >= logging::trivial::info
    );
}

struct BF {
                unsigned int b : 8;
                BF() : b(0) {}
};

int main(int, char*[])
{
    init();
    BF bf;
    BOOST_LOG_TRIVIAL(info) << "An informational severity message " << bf.b;
    return 0;
}
//]

与boost 1.61我得到一个编译错误:

不能绑定位域'bf。BF::b' to 'unsigned int&'

使用boost 1.57编译并运行代码(打印:[2016-09-19 20:21:33.018112][0x000007fd1d5be672] [info]一个信息严重性消息0)

注意:

  1. cout当然可以处理这个(所以我认为这不仅仅是一个向后兼容性问题,而是一个bug)
  2. boost 1.61可以处理const位域,例如BOOST_LOG_TRIVIAL(info) << "An informational severity message " << BF().b;

我正在寻找解决方法。建议吗?

最简单的解决方法是将位域转换为完整的整数。你可以通过强制转换来实现:

BOOST_LOG_TRIVIAL(info) << "An informational severity message "
    << static_cast< unsigned int >(BF().b);

我找到了一个解决方法-重载操作符<<对于所有无符号整数的record_ostream:

#include <sys/types.h>
namespace logging = boost::log;
typedef logging::basic_formatting_ostream<  logging::record_ostream::char_type > formatting_ostream_type;
logging::record_ostream& operator << (logging::record_ostream& strm, u_int8_t value) {
    static_cast< formatting_ostream_type& >(strm) << value;
    return strm;
}
logging::record_ostream& operator << (logging::record_ostream& strm, u_int16_t value) {
    static_cast< formatting_ostream_type& >(strm) << value;
    return strm;
}
logging::record_ostream& operator << (logging::record_ostream& strm, u_int32_t value) {
    static_cast< formatting_ostream_type& >(strm) << value;
    return strm;
}
logging::record_ostream& operator << (logging::record_ostream& strm, u_int64_t value) {
    static_cast< formatting_ostream_type& >(strm) << value;
    return strm;
}

整数被复制(按值获取),所以没有绑定问题