How to make a variadic macro for std::cout?

前端 未结 4 1183
北恋
北恋 2020-11-27 22:05

How would I make a macro that took a variable amount of arguments, and prints its out using std::cout? Sorry if this is a noob question, couldn\'t find anything that clarifi

4条回答
  •  一个人的身影
    2020-11-27 22:31

    When using variadic macros you need __VA_ARGS__ to expand all the arguments. The problem however is that those arguments are comma-separated. Presumabely it just separates arguments to a function call, but since macros works with just text you can actually use __VA_ARGS__ in other contexts as well, where a comma-separated list makes sense.

    The trick you can employ is to define your own comma operator for std::ostream (the type of std::cout). For example:

    #include
    #define LOG(...) std::cout , __VA_ARGS__ , std::endl
    
    template 
    std::ostream& operator,(std::ostream& out, const T& t) {
      out << t;
      return out;
    }
    
    //overloaded version to handle all those special std::endl and others...
    std::ostream& operator,(std::ostream& out, std::ostream&(*f)(std::ostream&)) {
      out << f;
      return out;
    }
    
    int main() {
      LOG("example","output","filler","text");
      return 0;
    }
    

    Now, the LOG invocation will expand to:

    std::cout , "example" , "output" , "filler" , "text" , std::endl;
    

    and the commas will invoke the overloaded comma operators.

    If you don't like overloaded operator, polluting all std::ostream-s, you can encapsulate std::cout with your own special logger class.

提交回复
热议问题