代码之家  ›  专栏  ›  技术社区  ›  markh44

有没有一个很好的方法来组合流操纵器?

  •  7
  • markh44  · 技术社区  · 15 年前

    cout << "0x" << hex << setw(4) << setfill('0') << 0xABC;
    

    这似乎有点冗长。使用宏有助于:

    #define HEX(n) "0x" << hex << setw(n) << setfill('0')
    
    cout << HEX(4) << 0xABC;
    

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

    2 回复  |  直到 15 年前
        1
  •  19
  •   stinky472    15 年前

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

    #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;
    }
    

    这使它更一般一点。可以使用上述函数的原因是 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;
    }
    

    但是,如果可以在编译时确定大小,那么最好使用函数模板[感谢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;
    }
    
        2
  •  4
  •   KenE    15 年前

    void write4dhex(ostream& strm, int n)
    {
        strm << "0x" << hex << setw(4) << setfill('0') << n;
    }
    
        3
  •  1
  •   vitaut    4 年前

    在C++ 20中,你可以使用 std::format 为了让这更不冗长:

    std::cout << std::format("0x{:04x}", 0xABC);  
    

    输出:

    0x0abc
    

    通过将格式字符串存储在常量中,还可以轻松地重用它。

    the {fmt} library 标准::格式 基于{fmt}还提供 print godbolt ):

    fmt::print("0x{:04x}", 0xABC); 
    

    免责声明 标准::格式