Variadic Templates in C++ -- Eli Bendersky

Save to:
Instapaper Pocket Readability

plusprofilephoto.pngA nice tutorial on a feature that leads to convenient and safe calling code:

Variadic Templates in C++

by Eli Bendersky

From the article:

Prior to C++11, the only way to write functions that take an arbitrary number of arguments was to use variadic functions like printf, with the ellipsis syntax (...) and the accompanying va_ family of macros. If you've ever written code using this approach you know how cumbersome it is. In addition to being type unsafe (all type resolution has to be done explicitly with casts in va_arg, at runtime), it's also tricky to get right. The va_ macros perform low-level memory manipulation, and I've seen a lot of code that segfaults because it isn't using them carefully enough.

But what always bothered me most with this approach is leaving something that is clearly known at compile-time, to run-time. Yes, when we write a variadic function we don't know all the ways it's going to be used. But when the compiler puts the whole program together, it does know. It sees perfectly well all the invocations of the function throughout the program, and all the possible argument types it gets passed (types are, after all, resolved at compile-time in C++).

Variadic templates

One of the new features of C++11 is variadic templates. Finally, there's a way to write functions that take an arbitrary number of arguments in a type-safe way and have all the argument handling logic resolved at compile-time, rather than run-time. Variadic templates can be used for much more than just functions that take an arbitrary number of arguments; in this article I want to demonstrate some of these capabilities...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.