In addition to generic template definitions, you can add a separate implementation for specific uses, for example:

// general template function
template<typename T>
void print(void) {
   std::cout << "Generic print" << std::endl;

// specialization of the function for <int> type
void print<int>(void) {
   std::cout << "Int print" << std::endl;

So, when used in following code:
void test(void) {

The output will be:
Generic print
Generic print
Int print 

Other forms

There are many ways to specialize a template, below are only a few examples:

// generic version - accepts any 2 types
template<typename T, typename U>
void show_specialization(T t, U u) {
   std::cout << "Generic version" << std::endl;

// special case - same type for both parameters
template<typename T>
void show_specialization(T t1, T t2) {
   std::cout << "Same type for both parameters" << std::endl;

// special case - both types are pointers
template<typename PT, typename PU>
void show_specialization(PT *pt, PU *pu) {
   std::cout << "Pointer types used" << std::endl;

// etc.

Last edited Nov 24, 2007 at 12:46 PM by migo, version 2


No comments yet.