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

后端 未结 4 1451
礼貌的吻别
礼貌的吻别 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

    You can use this kind of class:

    #include 
    
    using namespace std;
    
    class CustomOut
    {
    public:
    
        template
        CustomOut& operator<<(const T& obj)
        {
            cout << " my-cout " << obj;
            return *this;
        }
    
    };
    
    int main()
    {
        CustomOut mycout;
        mycout << "test" << 4 << "\n" << 3.4;
    }
    

    You'd need more code to use std::endl and other functors, so i've used here simple \n instead.

提交回复
热议问题