What's the difference between these two definitions of function templates?

83 Views Asked by At
template <typename Func, typename... Args>
  static void WraperFunc(Func func, Args &&... args) {
    SomeFunc(func, args...);
  }

vs

template <typename Func, typename... Args>
  static void WraperFunc(Func func, Args ... args) {
    SomeFunc(func, args...);
  }

Which is better and more recommended? Or is there an alternative which is better than both?

3

There are 3 best solutions below

2
On

The first one, but you need to forward your arguments during expansion by using std::forward<T>. This allows your parameter pack to be expanded while properly deducing your arguments.

template <typename Func, typename... Args>
static void WraperFunc(Func func, Args &&... args)
{
    // note that we use std::forward<Args>( args )... to perfect forward our arguments
    SomeFunc(func, std::forward<Args>( args )...);
}

As an example, say you have a function declared as follows:

template <typename T>
void some_func( T& ) {}

Attempting to use said function with a temporary value or rvalue will fail:

some_func( 5 );

This is due to the fact that 5 is a constant, which cannot be assigned to int&.

0
On

The Args && will accept lvalues, and rvalues by reference and enables them to be forwarded on maintaining their original value category. I would favour that version (and use std::forward).

template <typename Func, typename... Args>
  static void WraperFunc(Func func, Args &&... args) {
    SomeFunc(func, std::forward<Args>(args)...);
    //             ^^^^^^^^^^^^ Use of forward
  }

Note the idiomatic use of std::forward, it does not include the && of the Args&&.

There are a number of articles on the mechanics and use of std::forward and reference collapsing, here and the Scott Meyers classic on "forwarding (or universal) references".

0
On

Let's say you call your function with the following arguments:

void (*foo)(int, char, float) = /* ... */;
const int i = 0;
char j;
WraperFunc(foo, i, j, 0.42);

In the first case, it's equivalent to calling this function:

void WraperFunc(void (*foo)(int, char, float), int i, char c, float j) { /* ... */ }

In the second case it's equivalent to calling this function:

void WraperFunc(void (*foo)(int, char, float), const int& i, char& c, float&& j) { /* ... */ }

The second is recommended if you want to forward argument while avoiding copies (but use std::forward then!)