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.

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

  COMMENTS

0

No comment for this article.