xxxxxxxxxx
template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};
xxxxxxxxxx
#include <iostream>
using namespace std;
// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T> T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.0, 7.0)
<< endl; // call myMax for double
cout << myMax<char>('g', 'e')
<< endl; // call myMax for char
return 0;
}
xxxxxxxxxx
A template is a simple and yet very powerful tool in C++. The simple idea is to
pass data type as a parameter so that we don’t need to write the same code for
different data types.
For example, a software company may need sort() for
different data types. Rather than writing and maintaining the multiple codes,
we can write one sort() and pass data type as a parameter.
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The
second keyword can always be replaced by keyword ‘class’.
xxxxxxxxxx
#include <iostream>
using namespace std;
// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}
int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
cout << myMax<char>('g', 'e') << endl; // call myMax for char
return 0;
}
xxxxxxxxxx
#include <iostream>
using namespace std;
// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T> T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.0, 7.0)
<< endl; // call myMax for double
cout << myMax<char>('g', 'e')
<< endl; // call myMax for char
return 0;
}
xxxxxxxxxx
// C++ Program to demonstrate
// Use of template
#include <iostream>
using namespace std;
// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T> T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
// Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;
return 0;
}
xxxxxxxxxx
template <typename T> T myMax(T x, T y){
return (x > y) ? x : y;
}
int main(){
// Call myMax for int
cout << myMax<int>(3, 7) << endl;
// call myMax for double
cout << myMax<double>(3.0, 7.0) << endl;
// call myMax for char
cout << myMax<char>('g', 'e') << endl;
return 0;
}
xxxxxxxxxx
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
//Example:
template <class Type>
void Swap( Type &x, Type &y)
{
Type Temp = x;
x = y;
y = Temp;
}