Search code examples
c++c++11c++17fold-expression

Can I std::forward the arguments in fold expression?


In C++11 we have variadic templates, in which we can std::forward the arguments like in the following code

#include <utility>
#include <iostream>
#include <string>

void printVariadic()
{}
template<typename T, typename... Args>
void printVariadic(T&& arg, Args&&... args)
{
   std::cout << arg << "\n";
   printVariadic(std::forward<Args>(args)...); // here we forward the arguments
}

But, in C++17 we have fold expression (and from my understanding it doesn't make recurive function call until last argument).

template<typename ... Args>
void print(Args ... args)
{
    ((cout << args << "\n"), ...); // did we here miss the part of `std::forward`?
}

In the online examples, I couldn't see a std::forward ing of the arguments, when fold expression has used.

Can I forward the arguments in fold expression? Or don't we need it at all?

It might a dumb beginner qestion, still I couldn't find an answer in online.


Solution

  • Can I forward the arguments in fold expression?

    Yes

    template<typename ... Args>
    void print(Args && ... args)
    { // ...........^^
        ((cout << std::forward<Args>(args) << "\n"), ...);
    }
    

    The point isn't folding.

    The point is how do you receive an argument.

    If you receive it as value

    void print(Args ... args) // <-- by value
    

    you can't forward it (but you can move it)

    If you want forward it, you have to receive it as forwarding reference, that is with a template type and a &&

    template<typename ... Args>
    void print(Args && ... args) // <-- forwarding reference