Templates

Source files (for downloading):


Function Templates

A function template is not a function but a pattern for what could become a function.

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 i1 = 5, i2 = 9;
double d1 = 3.2, d2 = 9.7;
string s1("hello"), s2("goodbye");
 
cout << minimum(i1, i2) << endl;
cout << minimum<double>(d1, d2) << endl;
cout << minimum(s1, s2) << endl;
 
swapIt(i1, i2);
swapIt(d1, d2);
swapIt(s1, s2);
 
cout << "After swapIt, i1 = " << i1 << ", i2 = " << i2 << endl;
cout << "After swapIt, d1 = " << d1 << ", d2 = " << d2 << 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

What happens at compile time: function/class expansion

 

 

 

Compare to Java generics

 

 

 

 

 

 

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;