In C + +, the specificity of a template enables different processing of different data types:
For example, we want to sort the data of type int by a quick sort method.
Sort by insertion sort for data of float type
Template<typename t>
void sort (T arg[], int size) {
cout << "temp speclized use" << Endl;
}
template<> //Special
void sort<int> (int arg[], int size) {
cout << "int specliazed Template "<< Endl;
}
template<>
void sort<char> (char arg[], int size) {
cout << "char speclized template" << Endl;
}
int main () {
int array_int[5] = {1,2,3,4,5};
int size = 5;
Float Array_float[5] = {1.0, 2.0, 3.0, 4.0, 5.0};
Char array_char[5] = {1,2,3,4,5};
Sort<int> (array_int, size);
Sort<float> (array_float, size);
Sort<char> (Array_char, size);
System ("PAUSE");
return 0;
}
The output results are as follows:
int specliazed Template
Temp speclized Use
Char speclized template
The basic format of the special features is as follows:
A generic Sort program
template <class t>
void sort (T arr[], int size) {//
implement fast sort Code
}
// Template specification: Specifying a function of the char data type
template <>
void sort<char> (char arr[], int size)
{
//Implement count sort code
Also, template specificity applies to template classes:
For example, in a template class, you want to use a specific action on a class of type int:
Template<class t>
class Specialuse {public
:
specialuse () {
cout <<] General template Use "<< Endl;
}
};
Template<>
class Specialuse<int> {public
:
specialuse () {
cout << int Template use "<< Endl;
}
};
Use the following:
Specialuse<char> Charuse;
Specialuse<int> Intuse;
The output results are as follows:
General template Use
int template Use
The principle of template specificity:
When a template class or template function is written, if the compiler encounters a new data type or collection of data types, the compiler creates a copy of the template class or template function
The specificity of the template function will allow the compiler to first validate the template function or template class for this type