我正在使用 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/