Parametric Polymorphism (Genericity, C++ Templates) Flashcards

1
Q

What’s parametric polymorphism?

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the steps in the instantiation process of a template?

A
  1. Substitutes formal with actual template parameters
  2. Generates new object (.o/.obj) code
  3. A single (observable) instantiation per type unit. i.e Test instantiated at most 1 time.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

When does the compilation of a template occurs?

A
  • Partial compilation when the definition is read
    Validation of non template related code
  • Full compilation work done upon instantiation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Does the template definition must be in the source code?

A

yes. the template definition must be reachable by includes from the instantiation point.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Can a function be both virtual and templated?

A

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…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Is it possible to have a template argument which is not known at compile-time?

A

No. all parameters have to be known at compile-time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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”);
}

A

because n is defined before buff. not because of the initialization list order, if we change definitions order it will fail.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can string or double appear as template arguments?

A

no.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is template specialization?

A
Having a specific case for the templated class that is defined differently. 
example:
template
struct Pair {
  // T a, b; set; print; ...
};

template<>
struct Pair { … }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly