how to create template function 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: how to write a template c++
template <class myType>
myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
Example 3: template function in C++
#include <iostream>
using namespace std;
template <class T>
class mycontainer {
T element;
public:
mycontainer (T arg) {element=arg;}
T increase () {return ++element;}
};
template <>
class mycontainer <char> {
char element;
public:
mycontainer (char arg) {element=arg;}
char uppercase ()
{
if ((element>='a')&&(element<='z'))
element+='A'-'a';
return element;
}
};
int main () {
mycontainer<int> myint (7);
mycontainer<char> mychar ('j');
cout << myint.increase() << endl;
cout << mychar.uppercase() << endl;
return 0;
}