134

I was just writing a generic object factory and using the boost preprocessor meta-library to make a variadic template (using 2010 and it doesn't support them). My function uses rval references and std::forward to do perfect forwarding and it got me thinking...when C++0X comes out and I had a standard compiler I would do this with real variadic templates. How though, would I call std::forward on the arguments?

template <typename ...Params>
void f(Params... params) // how do I say these are rvalue reference?
{
    y(std::forward(...params)); //? - I doubt this would work.
}

Only way I can think of would require manual unpacking of ...params and I'm not quite there yet either. Is there a quicker syntax that would work?

PraAnj
  • 869
  • 1
  • 9
  • 27
Edward Strange
  • 39,707
  • 7
  • 69
  • 124

1 Answers1

194

You would do:

template <typename ...Params>
void f(Params&&... params)
{
    y(std::forward<Params>(params)...);
}

The ... pretty much says "take what's on the left, and for each template parameter, unpack it accordingly."

GManNickG
  • 478,574
  • 51
  • 478
  • 539
  • 1
    Add to that how the parameters should be passed. I think tutorials show `void f(Params&& ...params)` – UncleBens May 12 '10 at 17:32
  • 107
    On talk like a pirate day I use `void f(Ar&& ...arg)` – woolstar Jan 25 '14 at 07:41
  • Please explain the motivation of the choice of rvalue reference && (instead of & reference or just by value depending on situation) – DavidJ Mar 04 '20 at 00:46
  • 1
    @DavidJ I've taken the motivation as baked into the question. See however: https://stackoverflow.com/questions/3582001/advantages-of-using-forward – GManNickG Mar 04 '20 at 01:52
  • I really can not get the idea behind where ... should go – Nick Jul 16 '21 at 14:38
  • 1
    @DavidJ The && in this case is not an rvalue reference but a forwarding (or universal) reference. When used with templates it can bind to any reference type. https://blog.petrzemek.net/2016/09/17/universal-vs-forwarding-references-in-cpp/ – David Woo Aug 26 '21 at 11:33