Forwarding arguments with auto in C++20?

Viewed 285

In C++20, is the following function not ill-formed:

void f(auto&&... args) { /*...*/ }

and, if not ill-formed, is there a way to forward arguments in the body (without modifying the signature) in exactly the same fashion as the following function:

template<typename... Args>
void f(Args&&... args) {
    g(std::forward<Args>(args)...);
}

If so, what should replace the use of Args as the template argument to std::forward?

1 Answers

You can do it with the help of decltype.

void f(auto&&... args) {
    g(std::forward<decltype(args)>(args)...);
}

When being passed lvalues, decltype(args) yields type T&, std::forward would forward them as lvalues. When being passed rvalues, decltype(args) yields type T&&, std::forward would forward them as rvalues. Note that it's a little different with the template version, in which T is specified as template argument for std::forward; the effect (i.e. forwarding as rvalues) is the same for both cases.

Related