Introduction To C++ Templates and Exceptions
Introduction To C++ Templates and Exceptions
FunctionTemplate
TemplateParamDeclaration: placeholder
class typeIdentifier
typename variableIdentifier
Copyright 2006, The Ohio State University
Example of a Function Template
Template parameter
template<class SomeType>
(class, user defined
void Print( SomeType val ) type, built-in types)
{
cout << "***Debug" << endl;
cout << "Value is " << val << endl;
}
TemplateFunction Call
Template Functions
One Function Definition (a function template)
Compiler Generates Individual Functions
Class Template
TemplateParamDeclaration: placeholder
class typeIdentifier
typename variableIdentifier
Copyright 2006, The Ohio State University
Example of a Class Template
template<class ItemType>
class GList
{ Template
public: parameter
bool IsEmpty() const;
bool IsFull() const;
int Length() const;
void Insert( /* in */ ItemType item );
void Delete( /* in */ ItemType item );
bool IsPresent( /* in */ ItemType item ) const;
void SelSort();
void Print() const;
GList(); // Constructor
private:
int length;
ItemType data[MAX_LENGTH];
};
class GList_int
{
public: int
private: int
int length;
ItemType data[MAX_LENGTH];
};
int
Copyright 2006, The Ohio State University
Function Definitions for Members of a
Template Class
template<class ItemType>
void GList<ItemType>::Insert( /* in */ ItemType item )
{
data[length] = item;
length++;
}
// Instantiate a vector
vector<int> V;
// Insert elements
V.push_back(2); // v[0] == 2
V.insert(V.begin(), 3); // V[0] == 3, V[1] == 2
// Random access
V[0] = 5; // V[0] == 5