16. Templates
Templates is a feature in C++ which enables generic programming, with templates code-reuse becomes much easier.
Consider this simple example:
#include <string>
#include <iostream>
void printstring(const std::string& str) {
std::cout << str << std::endl;
}
int main()
{
std::string str("Hello World");
printstring(str);
}
Our printstring() takes a std::string as its first argument, therefore it can only print strings. Therefore, to print a character array, we would either overload the function or create a function with a new name.
This is bad, since the implementation of the function is now duplicated, maintainability becomes harder.
With templates, we can make this code re-usable, consider this function:
template<typename T>
void print(const T& var) {
std::cout << var << std::endl;
}
The compiler will automatically generate the code for whatever type we pass to the print function. This is the major advantage of templates. Java doesn't have templates but Java uses inheritance to achieve generic programming. For example in Java:
public static void printstring( Object o ) {
System.out.println( o );
}
You can pass in any object you want.
References:
- http://babbage.cs.qc.edu/STL_Docs/templates.htm Mirror at: http://www.mike95.com/c_plusplus/tutorial/templates
- This tells about #pragma template : - http://www.dgp.toronto.edu/people/JamesStewart/270/9697f/notes/Nov25-tut.html
- Very GOOD site: http://www.cplusplus.com/doc/tutorial/tut5-1.html http://www.cplusplus.com/doc/tutorial
- For certification of C++: go to http://examware.com and click on "Tutorials" and then C/C++ button
- C++ Open books: http://www.softpanorama.org/Lang/cpp.shtml and click on tutorials
- Templates tutorial : http://www.infosys.tuwien.ac.at/Research/Component/tutorial/prwmain.htm
Next Previous Contents