c++classtemplatesabstract-data-typetemplate-classes

Template Classes and Functions in C++


I have a question that confuses me. I know what is template and aim of it but I have some blank points on usage.

I have a Template class like that:

template <class elemType>
class SSorting {
public:

int seqSearch(const elemType list[], int length, const elemType& item);
};

When I code the member of a class function seqSearch I need to declare as:

template <class elemType>
int SSorting <elemType> :: seqSearch(const elemType list[], int length, const elemType& item){
    *statements*
}

Everything okay at this point. template says this is a function that inside a template class and int in front of the function means that the function will return an integer value, but the part that I don't understand is why we have to write SSorting <elemType> :: seqSearch instead of SSorting :: seqSearch. I already say this is a member of a template class and return type why I we need to say <elemType> again.


Solution

  • You should recall that class/function templates means that for each instantiation with a different template type, the compiler writes down another copy of the code, replacing elemType with the relevant type. Meaning, that if you are using in your code both SSorting<double> and SSorting<int>, you get two totally different types, with different names.

    Thus, the name of the class isn't SSorting, but SSorting<elemType>!