是否有一种结合流操纵器的好方法?

mar*_*h44 7 c++ iomanip

如果我想在流上输出4位数的固定宽度十六进制数,我需要做这样的事情:

cout << "0x" << hex << setw(4) << setfill('0') << 0xABC;
Run Code Online (Sandbox Code Playgroud)

这似乎有点长啰嗦.使用宏有助于:

#define HEX(n) "0x" << hex << setw(n) << setfill('0')

cout << HEX(4) << 0xABC;
Run Code Online (Sandbox Code Playgroud)

是否有更好的方法来组合操纵器?

sti*_*472 18

尽可能避免使用宏!它们隐藏代码,使事情难以调试,不尊重范围等.

您可以使用KenE提供的简单功能.如果你想获得所有的花哨和灵活,那么你可以编写自己的操纵器:

#include <iostream>
#include <iomanip>
using namespace std;

ostream& hex4(ostream& out)
{
    return out << "0x" << hex << setw(4) << setfill('0');
}

int main()
{
    cout << hex4 << 123 << endl;
}
Run Code Online (Sandbox Code Playgroud)

这使它更加通用.可以使用上述函数的原因是因为operator<<已经像这样重载:ostream& operator<<(ostream&, ostream& (*funtion_ptr)(ostream&)).endl和其他一些操纵者也是这样实现的.

如果要允许在运行时指定位数,我们可以使用一个类:

#include <iostream>
#include <iomanip>
using namespace std;

struct formatted_hex
{
    unsigned int n;
    explicit formatted_hex(unsigned int in): n(in) {}
};

ostream& operator<<(ostream& out, const formatted_hex& fh)
{
    return out << "0x" << hex << setw(fh.n) << setfill('0');
}

int main()
{
    cout << formatted_hex(4) << 123 << endl;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果可以在编译时确定大小,那么也可以使用函数模板[感谢Jon Purdy的建议]:

template <unsigned int N>
ostream& formatted_hex(ostream& out)
{
    return out << "0x" << hex << setw(N) << setfill('0');
}

int main()
{
    cout << formatted_hex<4> << 123 << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • +1我更喜欢操纵器到自由函数,因为它似乎更好地表达了意图.要使其完全通用,请将其写为模板`hex <N>`. (3认同)