【问题标题】:boost log non-const bitfield compilation error (backward compatibility issue)boost log 非常量位域编译错误(向后兼容性问题)
【发布时间】:2016-09-20 11:29:42
【问题描述】:

我以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' 绑定到 'unsigned int&'

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

注意:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 我想目前没有通过 boost::log 本身的解决方案,对吧?有计划在未来修复它吗?
    • 除非你想给Boost.Log打补丁,否则没有透明的解决方案。 svn.boost.org/trac/boost/ticket/11998 与您的问题同源,您也可以将您的案例添加到该票证中。
    • 如果您有宠物,我会非常高兴拥有它。 Tnx!
    • 我找到了一种解决方法 - 我在 record_ostream.hpp 中进行了搜索,并看到了您在此处添加的其他代码以及附加的有用说明并获得了方向...
    【解决方案2】:

    我找到了一种解决方法 - 重载运算符

    #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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 2010-09-05
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      相关资源
      最近更新 更多