C++ - Templates & Generics

Overview

Estimated time: 60–80 minutes

Write generic functions and types with templates. Learn how type deduction works and when to specialize.

Learning Objectives

  • Define function and class templates.
  • Understand template argument deduction and explicit arguments.
  • Use basic specialization when necessary.

Prerequisites

Function template

#include <iostream>
template <class T>
T add(T a, T b){ return a + b; }
int main(){
  std::cout << add(2,3) << "\n";         // T=int
  std::cout << add(2.5,3.1) << "\n";   // T=double
}

Expected Output: 5 5.6

Class template

#include <iostream>
template <class T>
struct Box { T value; };
int main(){
  Box<int> bi{42};
  Box<std::string> bs{"hi"};
  std::cout << bi.value << " " << bs.value << "\n";
}

Partial and full specialization (basics)

template <class T>
struct Traits { static constexpr const char* name = "generic"; };

template <>
struct Traits<int> { static constexpr const char* name = "int"; };

Beginner Boosters

#include <vector>
#include <iostream>
template <class T>
T first(const std::vector<T>& v){ return v.front(); }
int main(){ std::cout << first(std::vector<int>{1,2,3}) << "\n"; }

Common Pitfalls

  • Putting template definitions in .cpp files; templates must be visible at the point of instantiation (headers).
  • Overusing specialization when overloading or concepts would be clearer.

Checks for Understanding

  1. Why do template definitions typically live in headers?
  2. How does the compiler choose T for add(2,3)?
Show answers
  1. They must be visible at the point of instantiation so the compiler can generate code.
  2. Template argument deduction from parameter and argument types selects T=int.

Exercises

  1. Write a max_of function template that returns the larger of two values.
  2. Create a Pair<T,U> template with getters and a make_pair-like helper.