40

I want to use variadic template feature for my application but I don't want the objects to be passed by value (as objects are quite complex in my case). I want to pass them by reference (not as pointers).

void func()
{
}

template<typename Function1, typename... FurtherFunctions>
void func(Function1 f1, FurtherFunctions... further_functions)
{
    // doing some processing here...
}

How could I pass the arguments by reference and ensure that they are not copied?

usman
  • 1,285
  • 1
  • 14
  • 25

1 Answers1

46

Just say:

template <typename ...Args>
int myfunction(Args & ... args)
{
  /* ... */
}

Same for const Args & ... args, Args && ... args etc.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • What is the difference between Args & and Args && ? – usman Jun 15 '11 at 17:19
  • 2
    `Args &&` is an rvalue reference, which you will never need to write in your own code. I'm just mentioning it because it exists and you may occasionally [see it](http://stackoverflow.com/questions/6114067/how-to-emulate-c-array-initialization-int-arr-e1-e2-e3-behaviour/6272491#6272491). – Kerrek SB Jun 15 '11 at 17:22
  • 6
    Actually `&&` makes sense here, since you will likely want to use `std::forward`. – Alexandre C. Jun 15 '11 at 17:34
  • @Alexandre: Hm, I'm not sure, and you can't break anything by _not_ using rvalue references (don't say "auto_ptr"). If the OP wants to pass things by reference, chances are she wants to modify existing objects, so let's be safe. And if you know about rvalues and forward, you'll be able to fill in the blanks anyway... One step at a time, eh? :-) – Kerrek SB Jun 15 '11 at 17:46
  • of course you're right. If you don't plan to use `std::forward` then passing by reference is perfectly ok. Let me just add that perfect forwarding is one of the most delightful features of C++0x, and even if it is one of the most difficult to grasp, it is the perfect occasion to learn about it. – Alexandre C. Jun 15 '11 at 21:01
  • Note that `gcc` claims that the '...' are expected before the '&' when the order is not correct – Chris Feb 05 '19 at 16:02
  • I found that `Args && ...` is actually required. I used `Args & ...` to be able to receive atomic values (copy constructor disabled), but this caused the compiler to fail when r-values were being passed in by my unit tests. `Args && ...` seems to work for all situations, likely because C++ allows templated `&&` function arguments to accept both r- and l- values. – John Crawford Sep 21 '21 at 19:48