advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
advertisement
Average Rating: 4/5 | Rate this item | 7 users have rated this item.
 

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

  Next Page: Type-safe Variadic Functions
Page 1: Declaring a Variadic Template Page 3: Uses of Variadic Class Templates
Page 2: Type-safe Variadic Functions 
Please rate this item (5=best)
 1  2  3  4  5
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Help  |   Site Map  |   Network Map  |   About


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers