Browsed by
Month: January 2015

Using variadic templates in C++

Using variadic templates in C++

I’ve lately been working on C++ and my main task was to improve the design of the code and make it as generic as possible, removing the redundant code and so. To achieve this aim Templates and void pointers helped me a lot. In the following post I’m going to explain about variadic templates in C++.

Let’s me first give a brief intro about what templates actually are before moving on to variadic templates.

Quoting from Wikipedia “Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one”. That is, templates allow you to write a generic definition of such functions which are to be operated on different data types. For e.g.

I’m not continuing with templates as there’s already a lot of material about it on the internet.

One of the cool features of C++11 is what we call “Variadic Templates”. It allows us to define functions having variable number of templates parameters. A typical function using variadic templates looks like this :

This definition is pretty much like that of a function which accepts a variable number of parameters to it’s call. For e.g. our old friend printf().

Most of the other things can be found on the official C++ blog : http://www.cplusplus.com/articles/EhvU7k9E/

I’m heading on how to execute some particular code for each template parameter passed to the function via it’s call.

Let me first tell how a call to this function is made.

Note that, in the above call, even when the data types are not provided, the compiler will automatically deduce the data types from the parameters passed. They are necessary in the case when the parameters are not of type T in the definition.

Now let us write the implementation of our SampleFunction. The problem here is that data types are not available to us in the form of some list upon which we can iterate. The trick is to expand this argument pack by passing it to some dummy function. The following snippet of code illustrates this :

This code will print the size of every template parameter passed to the SameplFunction call. The above code works because the compiler expands the argument pack into the following form during the compilation :

So the output of the following call

will be

Though, there is one downside of the above approach. It doesn’t assert that the argument pack will be expanded from exact left-to-right sequence.
In case if you want to iterate in exactly the left-to-right sequence, the other approach is to use initialiser list.
The following code does the job :

I hope you liked the post.