Templates

Source files (for downloading):


Function Templates

Writing

template < generic_type_list >
 
// fctn def using types given in generic_type_list

where generic_type_list is a comma separated list of items of the form typename name (or class name)

Examples

// Templated function: minimum
// Requires < to be defined for type T
template <typename T>
const T & minimum(const T & x, const T & y) {
    return (x < y) ? x : y;
}
 

 
// Templated function: swapIt
// Requires operator= to be defined for type T
template <typename T>
void swapIt(T & x, T & y) {
    T temp;
    temp = x;
    x = y;
    y = temp;
}

Using

int x1 = 5, y1 = 9;
double x2 = 3.2, y2 = 9.7;
string s1("hello"), s2("goodbye");
 
cout << minimum(x1, y1) << endl;
cout << minimum<double>(x2, y2) << endl;
cout << minimum(s1, s2) << endl;
 
swapIt(x1, y1);
swapIt(x2, y2);
swapIt(s1, s2);
 
cout << "After swapIt, x1 = " << x1 << ", y1 = " << y1 << endl;
cout << "After swapIt, x2 = " << x2 << ", y2 = " << y2 << endl;
cout << "After swapIt, s1 = " << s1 << ", s2 = " << s2 << endl;
 
 

Class Templates

Example

template <typename Object>
class ObjectWrapper {
  public:
    ObjectWrapper(const Object & initValue = Object() ) :
      value(initValue) { }
 
    const Object & getValue() const { return value; }
     
    void setValue( const Object & newValue ); 
 
  private:
    Object value;
};
 
template <typename Object>
void ObjectWrapper<Object>::setValue( const Object & newValue ) {
    value = newValue;
}

Using

ObjectWrapper<int> obj1(8);
ObjectWrapper<double> obj2(3.14);
ObjectWrapper<string> obj3(s2);
 
obj1.setValue(2);
obj3.setValue(s1);

Compiling Templated Functions and Classes

Function/class expansion

 

 

 

 

 

 

 

 

 

 

 

 

Separate compilation

 

 

 

 

Inclusion model

 

 

 

 


Special Template Features

Multiple template parameters

template <typename KeyType, typename ValueType>
class Map {
	...
};

Specialized templates

template <typename T>
const T & minimum(const T & x, const T & y) {
	return (x < y) ? x : y;
}
 
template <>
const double & minimum<double>(const double & x, 
                               const double & y) {
	// do something special for doubles
}

Template non-type parameters

Template nontype parameters
template <typename Object, int size>
class Buffer {
	...
  private:
	Object buf[size];  
};
 
// in another file:
Buffer<string, 1024> buffer1;
Buffer<string, 2048> buffer2;