class template c++ code example
Example 1: c++ template function
template <class T>
void swap(T & lhs, T & rhs)
{
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
Example 2: function template
template <class T>
void swap(T & lhs, T & rhs)
{
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
void main()
{
int a = 6;
int b = 42;
swap<int>(a, b);
printf("a=%d, b=%d\n", a, b);
double f = 5.5;
double g = 42.0;
swap(f, g);
printf("f=%f, g=%f\n", f, g);
}
Example 3: templates classes in c++
#include <iostream>
using namespace std;
template <class T>
T GetMax (T a, T b) {
T result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax<int>(i,j);
n=GetMax<long>(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}
Example 4: how to write a template c++
template <class myType>
myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
Example 5: cpp how to create an object of template class
template class Graph<string>;
Example 6: 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);
}