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

前端 未结 4 1160
北恋
北恋 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:29

    You do not need preprocessor macros to do this. You can write it in ordinary C++. In C++11/14:

    #include 
    #include 
    
    void log(){}
    
    template
    void log(First && first, Rest && ...rest)
    {
        std::cout << std::forward(first);
        log(std::forward(rest)...);
    }
    
    int main()
    {
        log("Hello", "brave","new","world!\n");
        log("1", 2,std::string("3"),4.0,'\n');
    }
    

    Live demo

    In C++17:

    template
    void log(Args && ...args)
    {
        (std::cout << ... << args);
    }
    

    is all it takes. Live demo

    Output:

    Hellobravenewworld!
    1234
    

    Research variadic templates, parameter packs and fold expressions rather than variadic macros, which are rarely useful in modern C++.

提交回复
热议问题