2.3.4 Template specialization

Cope with special type features. If there is a good reason, why a compiler-generated template for a special type does not meet your requirements or would be more efficient or convient to use when implemented in another way, you can give the compiler a special implementation for this type - this special implementation is called template specialization. For example, when you know, that a shape-vector will always hold exactly one object, you can specialize the vector-template as follows:


class vector<shape> {
   shape v;
public:
   vector (shape& s) : v(s) { }
   shape& operator[] (int i) { return v; }
   int get_size() { return 1; }
};

Let's use it:


shape			MyShape;
vector<shape>	single_shape_vector (MyShape);

Template specializations can also be provided for template functions ([1], §r.14.5) and template operators.

Continue with section 3

Back to index


Johannes Weidl (J.Weidl@infosys.tuwien.ac.at) - Apr 16, 1996