Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

An Introduction to Variadic Templates in C++0x

Templates are one of the most powerful features in C++, and variadic templates make them even more powerful. Variadic templates in the C++0x standard library can greatly simplify the writing of type-safe code with variable numbers of arguments.


advertisement
f you've been programming in C++ for any time at all then you're familiar with variadic functions, functions (such as printf) that can take a variable number of arguments. C99 introduced variadic macros, which also take a variable number of arguments. C++0x takes this concept a step further with the introduction of variadic templates, where the number of template arguments is not specified when you write the template.

You declare the variadic part of a variadic template with an ellipsis (...) just like with a variadic function, though in this case it goes in the template parameter list:

template<typename ... Args> class my_class {};



You can then specify the arguments when you use the template. This approach is the same one you would use for a normal template, except that you can specify as many or as few arguments as you like:

my_class<int> mc1; my_class<double,char,std::string> mc2;

Just like with variadic functions, you don't even have to pass any arguments:

my_class<> mc3;

You can have other non-variadic template parameters too. After arguments have been allocated to the non-variadic parameters, the remainders constitute the parameter pack for the variadic parameter:

template<typename T,typename U,typename ... Args> class x {}; x<int,char,double,std::string> x1; // Args is <double,std::string> x<std::string,my_class<int> > x2; // Args is empty



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap