A Beginners guide to Templates - Part 2






3.33/5 (11 votes)
Jul 29, 2002
2 min read

88282
Using advanced template functionality
Introduction
In the first part of this Beginner's Guide, we handled function and class templates. For this part, I show you some more useful stuff that can be done with templates.
Overloading function templates
Function templates can be overloaded with other function templates as well as with normal functions. The compiler will step through the list of possible function templates and creates the appropriate template function. The result is complemented with other possible template functions. This list is being searched by normal overloaded functions for the one that fits best.
Using friend and templates inside a template
Class templates like the one used in part 1 can include other templates or classes as well as having other classes as friends. When a class template includes another class, there are two possibilities:
- The second inner class can be a common class. Therefore this inner class is also dependent from the template parameters. Otherwise the inner class is again a class template.
- The outer class template contains another template that is dependent from the outer class as well as its own template parameters. In this first example, we include some list processing into a class template:
template < class ElemType > class Tree { //... public: class Node { friend Tree < ElemType >; //... }; };
Here the inner class Node
is dependent from Tree
and
therefore gets its parameters. The outer class is defined as a friend
of Node
with a parameter list.
Template types
When using types that are declared within the scope of template parameters they have to be declared
using the word typename
:
template < typename T > class X { //... typename T::X theStuff; // T::X is the type //... }; class Test { //... class X { /* ... */ }; };
Without specifying the keyword typename
, the compiler expects T::X
to be a variable or constant and returns an error!
Element templates
When using element templates, it is possible e.g. to create a common
class Builder
that creates objects. This class provides an element function to allocate custom memory.
This element function will be implemented as template element function and can be used for any types:
class Builder { //... template < class T > static T* allocateMem(); };
Note: Template element functions can not be declared as virtual
!
Finally...
I hope I gave you an easy overview of the possibilities how templates can help you saving time while developing your projects. And remember, it also can save you a lot of code redundancy and typing errors!