Lesson 6 of 6
Practice & Quiz - Templates & Generic Programming
Test your mastery of function templates, class templates, specialisation, variadic templates, and perfect forwarding with a practical exercise and 5 quiz questions.
Practical Exercise - Generic min_max_range Utility
#include <iostream>
#include <vector>
#include <stdexcept>
#include <type_traits>
// ── Function template with enable_if constraint ──────────────
template<typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
struct Stats {
T min_val, max_val, sum;
size_t count;
T range() const { return max_val - min_val; }
double mean() const { return count ? (double)sum / count : 0.0; }
};
template<typename Iter>
auto compute_stats(Iter begin, Iter end)
-> Stats<typename std::iterator_traits<Iter>::value_type>
{
using T = typename std::iterator_traits<Iter>::value_type;
if (begin == end) throw std::invalid_argument("empty range");
Stats<T> s{*begin, *begin, T{}, 0};
for (auto it = begin; it != end; ++it) {
if (*it < s.min_val) s.min_val = *it;
if (*it > s.max_val) s.max_val = *it;
s.sum += *it;
++s.count;
}
return s;
}
// ── Variadic print - fold expression ─────────────────────────
template<typename... T>
void print_stats(const char* label, T&&... vals) {
std::cout << label << ": ";
((std::cout << vals << " "), ...);
std::cout << "\n";
}
int main() {
std::vector<int> iv{5, 2, 8, 1, 9, 3};
std::vector<double> dv{1.5, 2.7, 0.3, 4.1};
auto si = compute_stats(iv.begin(), iv.end());
auto sd = compute_stats(dv.begin(), dv.end());
print_stats("int min/max/range/mean", si.min_val, si.max_val, si.range(), si.mean());
print_stats("dbl min/max/range/mean", sd.min_val, sd.max_val, sd.range(), sd.mean());
// Works with raw arrays
double arr[] = {10.0, 3.0, 7.0};
auto sa = compute_stats(std::begin(arr), std::end(arr));
std::cout << "arr mean=" << sa.mean() << "\n";
return 0;
}Module Quiz
Template definitions must be in header files. Why?
Tip
Tip
Practice Practice Quiz Templates Generic Programming in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Function Templates, Class Templates, Full/Partial Specialization, Variadics & Zero-Overhead Generics
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Templates Generic Programming from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz Templates Generic Programming is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Finished this lesson?