C what is the process for defining a class template C what i
Solution
Template is a great feature in C++. We write code once and use it for any data type including user defined data types.
For example, sort() can be written and used to sort any data type items
// A generic sort function
template <class T>
void sort(T arr[], int size)
{
// code to implement Quick Sort
}
// Template Specialization: A function specialized for char data type
template <>
void sort<char>(char arr[], int size)
{
// code to implement counting sort
}
You can use templates to define functions as well as classes, let us see how do they work:
Function Template:
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.
Example:
#include <iostream>
using namespace std;
template <typename T>
void fun(const T&x)
{
static int count = 0;
cout << \"x = \" << x << \" count = \" << count << endl;
++count;
return;
}
int main()
{
fun<int> (1);
cout << endl;
fun<int>(1);
cout << endl;
fun<double>(1.1);
cout << endl;
}
Class Template:
Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:
template <class type> class class-name {
.
.
.
}
Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by using a comma-separated list.
Example:
#include <iostream>
using namespace std;
template <class T>
class Test
{
private:
T val;
public:
static int count;
Test() { count++; }
};
template<class T>
int Test<T>::count = 0;
int main()
{
Test<int> a;
Test<int> b;
Test<double> c;
cout << Test<int>::count << endl;
cout << Test<double>::count << endl;
return 0;
}

