Friday, April 12, 2013

Creating C++ templates


C++ Templates

C++ templates is a way to make your code generic, ie: you can call a function with any data type,
C++ uses this technique in its Abstract Data types such as vectors and lists,
to create a list of integers : list<int> intlist,
to create a list of strings: list<string> stringlist.

How to define functions using templates

Templates are implemented in C++ as Macro expansions, as they are not resolved in run time but actually in compile time,
consider the following function definition :

template <class myType>
myType GetMax (myType a, myType b) {
 return (a>b?a:b);
}
and to call the function:
int x,y;
GetMax<int>(x,y);

here template <class myType> is a parameter to the compiler to change “mytype” any where in the function with the word you define in the function call (here it is int”)


How to define classes using Templates

template <class myType>
call MyClass{
 public: Myclass();
}
template <class myType>
 MyClass::Myclass<myType>(){                                               
}
Note: we must always notify the compiler that we are using templates using template keyword template<class mytype>

No comments:

Post a Comment