how to use template class in c++ code example
Example 1: c++ class template
#include <vector>
template <class T1, class T2, typename T3, typename T4 = int>
class MyClass
{
public:
MyClass() { }
private:
T1 data;
T2 anotherData;
T3 variable;
}
int main(int argc, char **argv)
{
std::vector<int> array(10);
MyClass<int> object();
return (0);
}
Example 2: use of template in c++
#include <iostream>
using namespace std;
template <typename T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout << "Enter two integers:\n";
cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> f1 >> f2;
cout << Large(f1, f2) <<" is larger." << endl;
cout << "\nEnter two characters:\n";
cin >> c1 >> c2;
cout << Large(c1, c2) << " has larger ASCII value.";
return 0;
}