Using Recursion in Variadic Template Functions

Although recursion dooms show_list1() aspirations to be a useful function, properly used recursion provides a solution to accessing pack items. The central idea is to unpack the function parameter pack, process the first item in the list, then pass the rest of the list on to a recursive call, and so on, until the list is empty. As usual with recursion, it’s important to make sure that there is a call that terminates the recursion. Part of the trick involves changing the template heading to this:

template<typename T, typename... Args>void show_list3( T value, Args... args)

With this definition, the first argument to show_list3() gets picked up as type T and is assigned to value. The remaining arguments ...

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.