本文共 1727 字,大约阅读时间需要 5 分钟。
16.1.2. Defining a Class Template
template <class Type> class Queue { public: Queue (); // default constructor Type &front (); // return element from head of Queue const Type &front () const; void push (const Type &); // add element to back of Queue void pop(); // remove element from head of Queue bool empty() const; // true if no elements in the Queue private: // ... };
A class template is a template, so it must begin with the keyword templatefollowed by a template parameter list. Our Queuetemplate takes a single template type parameter named Type.
With the exception of the template parameter list, the definition of a class template looks like any other class. A class template may define data, function, and type members; it may use access labels to control access to those members; it defines constructors and destructors; and so on.In the definition of the class and its members, we can use the template parameters as stand-ins for types or values that will be supplied when the class is used.
Using a Class Template
In contrast to calling a function template, when we use a class template, we must explicitly specify arguments for the template parameters:
Queue<int> qi; // Queue that holdsints Queue< vector<double> > qc; // Queue that holds vectors of doubles Queue<string> qs; // Queue that holds strings
The compiler uses the arguments to instantiate a type-specific version of the class. Essentially, the compiler rewrites our Queueclass replacing Typeby the specified actual type provided by the user. In this case, the compiler will instantiate three classes: a version of Queuewith Type replaced by int, a second Queueclass that uses vector<double>in place of Type, and a third that replaces Typeby string.
转载地址:http://gyyii.baihongyu.com/