c++ - 如何使用 boost 格式打印位域

标签 c++ boost

我正在使用 boost::format 来打印结构。但是,boost::format 似乎无法处理“位字段”,请参见以下示例:

// Linux: g++ test.cc -lboost_system
#include <cstdio>
#include <iostream>
#include <boost/format.hpp>

struct bits_t {
    unsigned int io: 1;
    unsigned int co;
};

int main(void) {

    using std::cout;
    using boost::format;

    bits_t b; b.io = 1; b.co = 2;

    printf("io = %d \n", b.io); // Okay
    cout << format("co = %d \n") % b.co;  // Okay
    // cout << format("io = %d \n") % b.io;  // Not Okay
    return 0;

}

请注意我注释掉的第二个 cout,它尝试像 printf 那样打印出位字段,但编译器提示:

`error: cannot bind bitfield ‘b.bits_t::io’ to ‘unsigned int&’

我想知道我错过了什么?谢谢

最佳答案

问题是 boost::format 通过 const 引用(而不是拷贝)获取参数,并且引用不能绑定(bind)到位域。

您可以通过将该值转换为临时整数来解决此问题。一种简洁的方法是应用一元运算符+

 cout << format("io = %d \n") % +b.io;  // NOW Okay

关于c++ - 如何使用 boost 格式打印位域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16069198/

相关文章:

c++ - 编译C++程序的问题

c++ - 将 void 指针类型转换为 int 时出现段错误

c++ - 使用 MSVC2010 在动态 QT 中使用 RegOpenKey 和 RegEnumKey

c++ boost序列化如何防止不正确的文件崩溃

c++ - join() 上的 Boost 线程段错误

c++ - 通过 C++ Boost 的 VK API

c++ - boost::heap::arity,它是什么?

c++ - 对指针 vector 进行排序会更改 vector 拷贝中的数据?

c++ - 在结构体中打印数组

c++ - 在组合对之间找到共享元素的最佳方法