Using a Template Class
Merely including a template in a program doesn’t generate a template class. You have to ask for an instantiation. To do this, you declare an object of the template class type, replacing the generic type name with the particular type you want. For example, here’s how you would create two stacks, one for stacking int
s and one for stacking string
objects:
Stack<int> kernels; // create a stack of intsStack<string> colonels; // create a stack of string objects
Seeing these two declarations, the compiler will follow the Stack<Type>
template to generate two separate class declarations and two separate sets of class methods. The Stack<int>
class declaration will replace Type
throughout with int
, and the Stack<string>
class ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.