How to write a function wrapper for cout that allows for expressive syntax?

后端 未结 4 1453
礼貌的吻别
礼貌的吻别 2021-01-03 03:33

I\'d like to wrap std::cout for formatting, like so:

mycout([what type?] x, [optional args]) {
    ... // do some formatting on x first
    std:         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-03 03:58

    A variation from the answers:

    #include 
    
    using namespace std;
    
    class MyCout 
    {
    public:
      MyCout& operator()(bool indent) { 
        if ( indent ) cout << '\t'; 
        return *this;
      }
    
      template
      MyCout& operator<<(T t) {
        cout << t;
        return *this;
      }
    
      MyCout& operator<<(ostream& (*f)(ostream& o)) {
        cout << f;
        return *this;
      };
    };
    
    int main()
    {
      MyCout mycout;
      int x = 10;
      mycout(true)<< "test" << 2 << x << endl ;
    }
    

提交回复
热议问题