CS 202 Fall 2013 > Notes for Tuesday, November 5, 2013 |
CS 202 Fall 2013
Notes for Tuesday, November 5, 2013
Defining Templates [16.3]
Based on Non-Templates
When we write a template,
it is usually easiest to start with an ordinary function
(or, for a class template, an ordinary class)
and then turn it into a template.
For example, here is an ordinary function
that takes only int
parameters.
[C++]
// Ordinary (non-template) function int add(int a, int b) { return a + b; }
Here is a template version that takes any type that can be added.
[C++]
// Function-template version template<typename Addable> Addable add(Addable a, Addable b) { return a + b; }
Header & Source
Templates are used by the compiler to create new functions and classes. Thus, there is no separate compilation for templates—since there is no actual function or class yes, there is nothing to compile.
What this means in practice is that, when you write a software package with its own header and source files, all templates go in the header. If everything in your package is a template, then no separate source file is needed.
Class Templates [16.4]
A class template is much like a function template:
it gives the compiler a pattern for creating classes.
We have already seen a class template: vector
.
We can also write our own.
[C++]
template<typename Printable> class Messager { public: Messager(const Printable & p) _thing(p) {} void print() const { cout << _thing << endl; } private: Printable _thing; };
Now we can create a Messager
using just
about any constructor parameter we want.
However, unlike function templates,
we are required to specify template parameters explicitly.
[C++]
int main() { Messager<int> m(42); m.print(); // Prints 42 }
For today’s lab work, see the 11/5 Challenge.