C++ 11 feature: Parameter Pack and Variadic Templates

Parameter Pack:

Parameter pack is the new feature in C++11.

” is the syntax to create a parameter pack or to expand one .

Parameter pack is used to pack multiple parameters into single parameter.

This can be done by placing ellipsis “…” to the left of the parameter name.

Below example shows how to create a variadic parameter pack and expand a parameter pack.

Variadic Template:

Variadic Template is a new feature in C++11.

A template that accepts variable number of arguments, then that template is called as variadic template.

Before C++11, a template used to have fixed number of parameters that needed to be specified at the declaration.

Parameter pack will be used to create a variadic template.

Example 1: Variadic Template

In this below program we are adding 3 numbers and we are printing the function that will be called at the time.

#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <string>
#include <queue>
#include <vector>
#include <stack> 

using namespace std;

template <typename T>

T add_me(T v)
{
    cout <<"Function called is = "<<__PRETTY_FUNCTION__<<endl;
    return v;
}

// variadic function template that takes 
// variable number of arguments and 
// adds the value

template <typename T, typename... Args>
T add_me(T first, Args... args) // create a parameter pack
{
    cout <<"Function called is = "<<__PRETTY_FUNCTION__<<endl;
    return first + add_me(args...);  // parameter pack expansion
}

int main()
{
    int sum = add_me(1, 2, 3);
    cout<<"The integer sum is "<<sum<<endl;
    return 0;
}

Output:

Function called is = T add_me(T, Args...) [T = int, Args = <int, int>]
Function called is = T add_me(T, Args...) [T = int, Args = <int>]
Function called is = T add_me(T) [T = int]
The integer sum is 6
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *