std::print() and template parameter pack

133 Views Asked by At

Would be possible to print a template parameter pack using std::print? something like:

void func(auto... args){
    std::print("???", args...);
}

EDIT: if it wasn't clear: "???" means that I don't know what to put there, what construct to use in order to print the args passed to func(). What func() does is completely irrelevant and independent of that std::print() call.

Someting like: a call to func(a, b, c) to result in a call to std::print("{}{}{}", a, b, c)

SOLUTION: the closest one I could find (thanks @Passer By, I'll credit it to you if no better solution comes up in a few days):

auto func1(auto&&...args){/*...*/return 0;}//actual work on args
auto func0(auto&& arg, auto&&...args){
    //print args (no std::forward() here because we need the args later)
    std::print("{}", "args(");
    std::print("{}", arg);             //1st arg
    (std::print(", {}", args), ...);   //unfold the rest of the args
    std::println(")");
    //do something with the arguments
    return func1(std::forward<decltype(arg)>(arg), std::forward<decltype(args)>(args)...);
}
func0(1); //prints: args(1)
func0(2, "abc"); //prints: args(2, abc)
1

There are 1 best solutions below

6
Passer By On

You use a fold expression

void func(auto... args)
{
    (std::print("{} ", args), ...);
}

To get rid of the trailing space

void func(auto arg, auto... args)
{
    std::print("{}", arg);
    (std::print(" {}", args), ...);
}

Also, you should be forwarding arguments

template<typename T, typename... Ts>
void func(T&& arg, Ts&&... args)
{
    std::print("{}", std::forward<T>(arg));
    (std::print(" {}", std::forward<Ts>(args)), ...);
}