Variadic Templates
Variadic templates allow a C++ template to accept an arbitrary number of "extra" template arguments. When used with class templates, we can write templates like tuple (a generalized pair), or arbitrary-level compile-time vectors for template metaprogramming. Variadic templates also work in conjunction with function templates, so that function templates can take an arbitrary number of function arguments. In this sense, variadic templates provide the same capabilities as C's variadic functions, but in a type-safe manner. For instance, one can implement a simple, type-safe printf with the following code:
- void printf(const char* s) {
- while (*s) {
if (*s == '%' && *++s != '%')
- throw std::runtime_error("invalid format string: missing arguments");
std::cout << *s++;
template<typename T, typename... Args> void printf(const char* s, const T& value, const Args&... args) {
- while (*s) {
if (*s == '%' && *++s != '%') {
std::cout << value; return printf(++s, args...);
std::cout << *s++;
- while (*s) {
More information is available at http://www.generic-programming.org/~dgregor/cpp/variadic-templates.html
Personnel
- Douglas Gregor, Indiana University
Delivery Date
- Compiler patches available as of 2006-09-13, revised on 2006-09-19:
C++ front end: http://gcc.gnu.org/ml/gcc-patches/2006-09/msg00811.html
Command-line options, docs: http://gcc.gnu.org/ml/gcc-patches/2006-09/msg00812.html
Compiler tests: http://gcc.gnu.org/ml/gcc-patches/2006-09/msg00813.html
- libstdc++ patches available as of 2006-09-19:
libstdc++ TR1: http://gcc.gnu.org/ml/gcc-patches/2006-09/msg00814.html
Benefits
- We can greatly improve our implementation of Library TR1 in libstdc++, eliminating many preprocessor hacks, simplifying the code, and removing hard-coded limitations on the number of parameters used. This should also decrease compile time for the library significantly.
Dependencies
- None.
Modifications Required
- The language changes are limited to the C++ front end, with most modifications being made to the parser (cp/parser.c) and template system (cp/pt.c). The library changes will be limited to the TR1 section of the library (include/tr1).