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

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

    This comes easy with variadic template arguments:

    template 
    void print(T t)
    {
        std::cout << t;
    }
    
    template 
    void print(T t, Args... args)
    {
        std::cout << t << std::endl;
        print(args...);
    }
    
    int main()
    {
        std::cout << std::boolalpha;
        print(3, 's', true, false);
    }
    

    Output:

    3
    s
    true
    false

    Live Demo

提交回复
热议问题