This blog post is about C++ Variadic Template example , introduced in C++11. So what is c++ variadic template?

Variadic templates are template that take a variable number of arguments. Before c++11 standard we had class templates or function templates which take only fixed number of arguments.

C++11 allows class template or function template to take an arbitrary number of arguments of any type. Let us write a template function which takes any number of integers arguments and print sum of all integers.

#include<iostream>

int sum()
{
    return 0;
}

template<typename T, typename ... Args>
int sum(T a, Args ... args)
{
    return a + sum(args...);
}

int main()
{
    int res = sum(1, 2, 3, 4);
    std::cout << res << std::endl;
    return 0;
}

Compile using:

g++ -std=c++11 sample.cpp

Run: #./a.out

Output : 10

Variadic Class Template Example

Like variadic function template we can create variadic class template.

template<typename T, typename ... Args>
class foo
{
    public:
        foo(T arg, Args ... args);
};
  1. To instantiate the class template we must specify at least the first argument and followed by zero or more arguments. Let us see an example.
#include<iostream>
using namespace std;

template<typename T, typename ... Args>
class foo
{
    public:
        foo(T arg, Args ... args)
        {
        }// constructor

        template<typename T1, typename ... args>
        void print(T1 arg, args ... arglist)
        {
            cout << arg << endl;
            print(arglist...);//Parameter expansion
        }

        void print()
        {
            cout << endl;
        }
};

int main()
{
    cout << "create class object" << endl;
    foo<int, char, float> foo_obj(1, 'm', 2.2);
    foo_obj.print(1, 'm', 2.2);
    return 0;
}

 

Learn c++ 11 features with sample code

Learn c++11 constexpr



Related Contents to follow