Tuesday, May 27, 2008

C++ Templates

Leave a Comment
What are templates?
  • Templates provide a mechanism to handle different data types in the same function or class.
  • When used in functions they are referred as function templates.
  • When used with classes they are referred as class templates.
  • Template arguments are specified either with keywords "class" or "typename".
  • Main advantages of templates are that they make the code listing smaller and maintainence burden is reduced since changes are done at one place only.

EXAMPLE: Demonstrate the usage of function templates.


#include <iostream>
using namespace std;

// Template function
template <typename T>
T max ( T a, T b ) {
return a<b?b:a;
}

// Overloaded
template <typename T>
T max ( T a, T b, T c ) {
return max(max(a,b),c);
}

// Args of different types
template <typename T, typename S>
void func ( T a, S b ) {
cout << a << " " << b << endl;
}

void main()
{
// Call to 2 arg template function
cout << max(1,2) << endl;
cout << max<int>(1,2) << endl;
cout << max(1.1,2.1) << endl;
cout << max<double>(1,2.1) << endl;
cout << max(static_cast<double>(1),2.1) << endl;
cout << max("hello", "world") << endl;

/* Compilation error when different types are used
cout << max(1, 1.2) << endl;
Error E2285 template.cpp 26: Could not find a match for 'max<_T>(int,double)' in function main()
*/

// Call to overloaded template function
cout << max(1,2,3) << endl;

// Call to template function with different arg types
func(1, 1.2);
}

OUTPUT:
2
2
2.1
2.1
2.1
world
3
1 1.2


EXAMPLE: Demonstrate the usage of class templates.


#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;

template <typename T>
class MyClass {
vector<T> data;

public:
void Add(T& a) {
data.push_back(a);
}

T Get() {
if ( data.empty() )
{
throw out_of_range("Out of range");
}
return data.back();
}
};

void main()
{
// Class used with int
int val1 = 100, val2 = 200;
MyClass<int> intObj;
intObj.Add(val1);
intObj.Add(val2);
cout << intObj.Get() << endl;

// Class used with string
string str1 = "Hello", str2 = "World";
MyClass<string> strObj;
strObj.Add(str1);
strObj.Add(str2);
cout << strObj.Get() << endl;
}

OUTPUT:
200
World
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment