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.


#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


#include "vtemp.h"

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

hello world 123 1.23

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s