Quiz 12 — Templates¶
Ten questions on writing a shape of code once and letting the compiler fill in the type.
Attempt all of them closed-book, then mark yourself against the answers.
Concepts: function and class templates · instantiation · deduction · non-type
parameters · where a definition lives · templates vs virtual.
Q1. (MCQ) When is a function template turned into real code?
- A. when the header is written
- B. when the compiler sees a call with concrete types
- C. at link time
- D. at run time
Q2. (true/false) The definition of a template used in another translation unit may
safely live only in a .cpp file.
Q3. (multiple-select) Which of these can be a non-type template parameter? Select all that apply.
- A.
int N - B.
bool Flag - C.
std::string Name - D.
double Ratio
Q4. (predict) Write the three output lines.
#include <iostream>
#include <string>
template <typename T>
T larger(T a, T b) { return (a > b) ? a : b; }
int main() {
std::cout << larger(3, 9) << '\n';
std::cout << larger(2.5, 1.5) << '\n';
std::cout << larger<std::string>("apple", "pear") << '\n';
}
Q5. (predict) Write the two output lines.
#include <iostream>
#include <string>
#include <vector>
template <typename T>
class Registry {
public:
void add(const T& value) { items_.push_back(value); }
std::size_t size() const { return items_.size(); }
const T& at(std::size_t i) const { return items_[i]; }
private:
std::vector<T> items_;
};
int main() {
Registry<int> numbers;
numbers.add(10);
numbers.add(20);
Registry<std::string> names;
names.add("Ada");
std::cout << numbers.size() << ' ' << names.size() << '\n';
std::cout << numbers.at(1) << ' ' << names.at(0) << '\n';
}
Q6. (debug) Both files compile, but the program does not link. Explain why and give the fix.
// widget.h
#pragma once
template <typename T>
T twice(T value);
// widget.cpp
#include "widget.h"
template <typename T>
T twice(T value) { return value + value; }
// main.cpp
#include "widget.h"
#include <iostream>
int main() { std::cout << twice(21) << '\n'; }
Q7. (analysis) Ring<int, 4> and Ring<int, 8> are different types. What does
that tell you about the non-type parameter N?
Q8. (short answer) What is instantiation, and why does it force a template's definition into a header?
Q9. (design) A course needs one store for marks keyed by student id, and later another for counts keyed by the same id. State the template's parameters, the container you would use, and one requirement you must document about the key type.
Q10. (analysis) A type has two implementations that differ per record kind. Give one
reason to reach for a template and one reason to prefer virtual instead.
Scoring: mark yourself with the answers, then read the self-assessment guide.