Notes on C++ variadic templates

Variadic templates is a class or function template that allows an arbitrary number of arguments in a type-safe manner. Variadic template has a recursive structure, where each recursion reduces the number of arguments.

vtemp.h

#include <iostream>

// base case
template<typename T>
void log(T val)
{
 std::cout << val << std::endl;
}

// recursive case
template<typename T, typename... Args>
void log(T val, Args... args) // Args... args signifies a parameter pack. i.e. an arbitrary number of parameters
{
 std::cout << val << " ";
 log(args...); // args... expands the parameters
}

main.cpp

#include "vtemp.h"

int main()
{
  log("hello", "world", 123, 1.23);
}

//Output:
hello world 123 1.23
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s