Variadic Templates

From C++11 on, you can use variadic templates functions with the following syntax:

template< typename T, typename... A >

This, combined with function overloading (where the same named function taking different parameters) means we can design a class that operate on a list of different types of objects with a single function.

Example

Given a class that works with different types of resources, you may use overloaded functions with cleverly chosen function names so that the code is more readable. For example, if my class reads data from different inputs, I will overload read() to accept parameters of different types:

class A;
class B;
class C;

class Me 
{
public:
  void read( A* );
  void read( B* );
  void read( C* );
};

This make it obvious what the class is doing, because actual code that make use of Me will look like:

A* bookA = ...;
B* screenB = ...;
C* signC = ...;

Me me;
me.read(bookA);
me.read(screenB);
me.read(signC);

We can make this code even more readable by combining the last 3 function calls into one by implementing an additional function with variadic templated read() like this:

template< typename T, typename... A >
void read( T* first, A&&... rest ) {
  read(first);
  read(std::forward<A>(rest)...);
}

The function above will go through the list, deal with first element using overloaded functions, and repeat until there is nothing left. We can then rewrite the 3 read() function calls:

read(bookA, screenB, signC);