template function in class in C++
Summary
When implementing template functions as class members in C++, a critical rule is to place the full definition within the header file, not a separate .cpp source file. This is necessary for the compiler to instantiate the template for different types at compile time. While the declaration resides within the class body, the definition can be placed outside the class declaration but still within the same header. An example demonstrates this with a static qsort template function defined directly in Sorter.h, ensuring proper compilation and linkage.
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.
No comment for this article.