【发布时间】:2013-07-17 01:37:48
【问题描述】:
我经常做这样的事情:
uint8_t c=some_value;
std::cout << std::setfill('0') << std::setw(2);
std::cout << std::hex << int(c);
std::cout << std::setfill(' ');
(特别是在转储调试信息时)。有一些可操纵的东西我可以像这样放入流中不是很好吗:
std::cout
这一切都可以吗?有人知道怎么做吗?
我已经完成了这项工作,但希望有一个更简单的方法:
#include <iostream>
#include <iomanip>
class hexcdumper{
public:
hexcdumper(uint8_t c):c(c){};
std::ostream&
operator( )(std::ostream& os) const
{
// set fill and width and save the previous versions to be restored later
char fill=os.fill('0');
std::streamsize ss=os.width(2);
// save the format flags so we can restore them after setting std::hex
std::ios::fmtflags ff=os.flags();
// output the character with hex formatting
os << std::hex << int(c);
// now restore the fill, width and flags
os.fill(fill);
os.width(ss);
os.flags(ff);
return os;
}
private:
uint8_t c;
};
hexcdumper
hexb(uint8_t c)
{
// dump a hex byte with width 2 and a fill character of '0'
return(hexcdumper(c));
}
std::ostream& operator<<(std::ostream& os, const hexcdumper& hcd)
{
return(hcd(os));
}
当我这样做时:
std::cout << "0x" << hexb(14) << '\n';
- hexb(c) 被调用并返回一个 hexcdumper,其构造函数保存了 c
- 重载运算符
- hexcdumper 的 operator() 为我们做了所有的魔法
- hexcdumper::operator() 返回后,重载的操作符
在输出中,我看到:
0x0e
有没有更简单的方法来做到这一点?
帕特里克
【问题讨论】:
-
您认为您的解决方案有什么问题?对我来说看起来不错,如果它可以满足您的需求。 优雅被夸大了!!