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

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

#include <iostream>
#include <utility>

void log(){}

template<typename First, typename ...Rest>
void log(First && first, Rest && ...rest)
{
    std::cout << std::forward<First>(first);
    log(std::forward<Rest>(rest)...);
}

int main()
{
    log("Hello", "brave","new","world!\n");
    log("1", 2,std::string("3"),4.0,'\n');
}

Live demo

In C++17:

template<typename ...Args>
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++.

Leave a Comment