1

I've been trying to understand the difference between Ts&&... and Ts&... for variadic functions, but can't find any explanations.

What are the differences between the two, and when would I use one over the other?

user3791372
  • 4,445
  • 6
  • 44
  • 78
  • A single `&` is a parameter passed by reference. The latter is an [`rvalue` reference](http://stackoverflow.com/questions/5481539/what-does-t-double-ampersand-mean-in-c11) – Cory Kramer Aug 14 '14 at 20:40
  • 1
    @Cyber In the special case of `T&&` where `T` is deduced, it can also bind to an lvalue (because the `T` can be deduced to `U&`) – Angew is no longer proud of SO Aug 14 '14 at 20:41

1 Answers1

1

It's the same as the difference between T& and T&&.

Ts&... only binds to lvalues. Ts&&... binds to both lvalues and rvalues and can be used to implement perfect forwarding.

Usually you'll probably want Ts&&... since it's hard to imagine why a function should be specified to accept arbitrarily many lvalues of arbitrary type, but not any rvalues. Functions that contain a Ts&&... are usually functions like emplace member functions that forward all the arguments to another function, such as a constructor.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • A typesafe version of `printf` would be one case where you might prefer to take the arguments by `const &`... Otherwise you might end up with bloated executables: `safe_printf("%d\n", 1); int a = 5; safe_print("%d\n", a);` would have two overloads if the argument is `T&&` but only one if it is `T&` – David Rodríguez - dribeas Aug 14 '14 at 21:34
  • @DavidRodríguez-dribeas Good point! But at least `const Ts&...` binds to rvalues too :-) – Brian Bi Aug 14 '14 at 21:39
  • I'm now more confused and still not sure as to when I should choose to use Ts&&... over Ts&...! – user3791372 Aug 15 '14 at 08:22
  • @user3791372 Why don't you tell us what kind of function you're writing? – Brian Bi Aug 15 '14 at 16:46
  • I did a lot of reading about Ts&& vs T& today, and I think I now understand. general rule to use && over & as it allows data to be passed around destructively and will be faster as it doesn't invoke constructor copy's as far as I understand. – user3791372 Aug 15 '14 at 16:50