What’s parametric polymorphism?
Allows definitions to be parametrized at compile-time
- Such a definition is actually a “compile-time function” that returns a new program element (method, class, etc.)
Template parameters =
The “function”’s arguments
Instantiation of a template =
evaluating the “function”
What are the steps in the instantiation process of a template?
When does the compilation of a template occurs?
Does the template definition must be in the source code?
yes. the template definition must be reachable by includes from the instantiation point.
Can a function be both virtual and templated?
No. if it was possible we would have problems, for example:
struct Base {
template
virtual void f(T) { … }
};
Base is compiled once as it is not templated, but how many entries should it’s vtable hold?
we don’t know, because f is different then f and from f…
Is it possible to have a template argument which is not known at compile-time?
No. all parameters have to be known at compile-time.
Why the following initialization works?
template
class Array {
size_t n; Type* buff;
public:
Array(size_t n_) : n(n_), buff(new Type[n]) {
if (buff == NULL) error(“Memory failure”);
}
because n is defined before buff. not because of the initialization list order, if we change definitions order it will fail.
Can string or double appear as template arguments?
no.
What is template specialization?
Having a specific case for the templated class that is defined differently. example:
template
struct Pair {
// T a, b; set; print; ...
};template<>
struct Pair { … }