template function in class in C++

  Pi Ke        2011-08-07 09:39:56       2,863        0    

We can define template function in a class, but one thing we should pay attention to is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.

Example
//Sorter.h
#pragma once
class Sorter
{
public:
    Sorter(void);
    ~Sorter(void);

    template <class type> static void qsort(type arr[],int start,int end);
};

template <class type> static void Sorter::qsort(type arr[],int start,int end){
    int mid=(start+end)/2;
    type mid_value=arr[mid];
    int i=start,j=end;
   
    do{
        while(arr[i]<mid_value&&i<end){
            i++;
        }
        while(arr[j]>mid_value&&j>start){
            j--;
        }
       
        if(i<=j){
            type tmp=arr[i];
            arr[i]=arr[j];
            arr[j]=tmp;
            i++;j--;
        }
    }while(i<j);
   
    if(i<end){
        qsort(arr,i,end);
    }
   
    if(j>start){
        qsort(arr,start,j);
    }
}

The definition should not be in Sorter.cpp file.

C++  TEMPLATE FUNCTION  CLASS  DEFINITION  D 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Where design meets implementation