boost log non-const位域编译错误(向后兼容性问题)

时间:2016-09-20 11:29:43

标签: c++ compiler-errors backwards-compatibility bit-fields boost-log

我从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我遇到了编译错误:

  

无法将bitfield'bf.BF::b'绑定到'unsigned int&amp;'

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

注意:

  1. cout当然可以处理这个问题(所以我认为这不仅仅是向后兼容性问题,而是一个错误)
  2. boost 1.61可以处理const位域,例如BOOST_LOG_TRIVIAL(info) << "An informational severity message " << BF().b;
  3. 我正在寻找解决方法。 建议?

2 个答案:

答案 0 :(得分:1)

最简单的解决方法是将位域转换为完整整数。你可以用演员表来做到这一点:

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

答案 1 :(得分:0)

我找到了一个解决方法 - 重载运算符&lt;&lt;对于所有无符号整数的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;
}

整数被复制(按值取值),因此没有绑定问题