C++十六进制整数的自定义 I/O 操纵器
C++ Custom I/O manipulator for hexadecimal integers
我正在尝试用C++编写一个自定义 I/O 操纵器,它可以根据提供的整数的大小以 0xFFFF
的形式编写格式良好的十六进制。
例如:
-
char c = 1
变得0x01
-
short s = 1
变得0x0001
等等。在我的代码中找不到错误,即打印垃圾:
#include <iostream>
#include <iomanip>
class hexa_s
{
mutable std::ostream *_out;
template<typename T>
const hexa_s& operator << (const T & data) const
{
*_out << std::internal << std::setfill( '0' ) << std::hex << std::showbase << std::setw( sizeof( T ) * 2 ) << data;
return *this;
}
friend const hexa_s& operator <<( std::ostream& out, const hexa_s& b )
{
b._out = &out;
return b;
}
};
hexa_s hexa( )
{
return hexa_s( );
}
int main()
{
int value = 4;
std::cout << hexa << value << std::endl;
return 0;
}
此行
std::cout << hexa << value << std::endl;
写入一个指针(指向函数六)。应调用该函数。
这绝不是批评。在我看来,编写io操纵器并不是一件小事。有许多"假设"和"陷阱"。
我可能选择这样做。你觉得怎么样?
#include <iostream>
#include <utility>
#include <limits>
#include <iomanip>
// in the general case, return a value unchanged
template<class Integral> auto as_integer(Integral i) { return i; }
// but in the case of chars, we must convert them to integers
// otherwise operator<< treats them as characters and does not
// obey the hex iomanipulator
auto as_integer(char c) { return int(c) & 0xff; }
auto as_integer(unsigned char c) { return unsigned(c) & 0xff; }
// This is a basic hex printer for any integral
template<typename Integral>
struct hex_printer
{
static constexpr size_t hex_digits = sizeof(Integral) * 2;
hex_printer(Integral i) : _i(i) {}
std::ostream& operator()(std::ostream& os) const
{
auto flags = os.flags();
try {
os << std::setfill('0') << std::setw(hex_digits) << std::hex << as_integer(_i);
}
catch(...) {
os.flags(flags);
throw;
}
os.flags(flags);
return os;
}
Integral _i;
};
template<typename Integral>
inline std::ostream& operator<<(std::ostream& os, hex_printer<Integral> const& hp)
{
return hp(os);
}
template<typename Integral>
auto neat_hex(Integral i) {
return hex_printer<std::decay_t<Integral>>(i);
}
int main()
{
int x= 0xf045;
short y = 0x6fa;
std::int64_t z = 0xe32;
std::uint8_t w = 0xde;
using namespace std;
cout << neat_hex(x) << " " << neat_hex(y) << " " << neat_hex(z) << " " << neat_hex(w) << endl;
return 0;
}
示例输出:
0000f045 06fa 0000000000000e32 de
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何正确实现和访问运算符的各种自定义枚举器
- flutter:即使shouldRepaint()返回true,自定义画家也不会重新绘制
- 自定义先决条件对移动分配运算符有效吗
- 使用VS Code和CMake Tools运行自定义命令
- C++自定义流操纵器,用于更改流上的下一个字符串
- 如何使用自定义流操纵器在类实例中保存数据
- 如何键入用于const对象的自定义io操纵器
- 如何实现接受参数的自定义流操纵器?
- 如何从类中返回自定义数组项目并操纵其属性?C
- 粘性自定义流操纵器
- 类的自定义操纵器
- C++十六进制整数的自定义 I/O 操纵器
- Android:如何将自定义对象的数组列表传递给c++代码,并使用JNI在Java代码中获得这些对象的操纵数组列表
- 自定义流操纵器,用于在任何基中流式传输整数
- 如何实现自动添加分隔符的自定义粘性操纵器