Notes
All notes

Templates and Language Features (C++ Core #5)

Templates are compile-time code generation. auto, decltype, lambdas, and constexpr are the features built on the same idea: let the compiler deduce or compute something so you do not repeat it. Move semantics is the runtime half of the story: distinguishing temporaries from objects you still need.

Function templates

A function template is a recipe for a family of functions. The compiler generates a concrete function for each set of template arguments it sees.

template <class T>
T maxOf(T a, T b) { return a > b ? a : b; }

maxOf(3, 7);          // T = int
maxOf(2.5, 1.5);      // T = double
maxOf<int>(3, 7);     // explicit

maxOf(1, 2.5);        // error: T deduced as int and double

Deduction uses the argument types. That last line fails because the two arguments imply different Ts; the fix is two parameters:

template <class A, class B>
auto maxOf(A a, B b) { return a > b ? a : b; }   // C++14 return deduction

Templates are instantiated at compile time, so the definition must be visible where they are used. That is why template definitions live in headers, not in .cpp files: the compiler needs the body to generate the code.

QQuestionWhy does maxOf(1, 2.5) fail to compile?
ASolution

Template argument deduction requires both parameters to give the same T. int and double conflict, and deduction does not apply conversions.

Class templates

template <class T>
class Box {
    T value;
public:
    explicit Box(T v) : value(std::move(v)) {}
    T get() const { return value; }
};

template <class T>
T Box<T>::get() const { return value; }   // out-of-line member: repeat the header

Box<int> b(5);
Box<std::string> s("hi");

Non-type parameters allow compile-time sizes:

template <class T, size_t N>
struct Array {
    T data[N];
    constexpr size_t size() const { return N; }
};

Array<int, 10> a;
static_assert(sizeof(a.data) == 40);

Default arguments and variadic templates extend the same mechanism:

template <class T = int> struct Counter { T n = 0; };

template <class... Ts>
void printAll(const Ts&... xs) { ((std::cout << xs << ' '), ...); }  // C++17 fold
QQuestionWhere do you put the definition of a class template’s member

function?

ASolution

In the header, after the class definition, with the template <...> line repeated. If it goes in a .cpp, other translation units cannot instantiate it.

Template specialization

A full specialization replaces the implementation for one concrete type. A partial specialization replaces it for a family of types (only class templates).

template <class T>
struct Printer {
    static void print(const T& v) { std::cout << v; }
};

template <>                        // full specialization
struct Printer<bool> {
    static void print(bool b) { std::cout << (b ? "true" : "false"); }
};

template <class T>                 // partial: any pointer
struct Printer<T*> {
    static void print(T* p) { std::cout << "ptr " << p; }
};

Since C++17, if constexpr often replaces specialization for function templates:

template <class T>
std::string describe(const T& v) {
    if constexpr (std::is_pointer_v<T>) return "pointer";
    else if constexpr (std::is_integral_v<T>) return "integer";
    else return "other";
}

if constexpr discards the untaken branch at compile time, so code that would not compile for that type is fine as long as it is in the discarded branch.

QQuestionCan you partially specialize a function template?
ASolution

No. Only class templates (and variable templates) can be partially specialized. Function templates use overloading or if constexpr instead.

Static data members in templates

Each instantiation has its own copy of a static member. Box<int>::count and Box<double>::count are different objects.

template <class T>
struct Counter {
    static int count;
};
template <class T>
int Counter<T>::count = 0;        // definition, one per T

Counter<int>::count++;
Counter<double>::count++;
std::cout << Counter<int>::count;      // 1

Since C++17 you can make it inline and define it in the class:

template <class T>
struct Counter {
    inline static int count = 0;
};

Inside a class template, Counter alone means Counter<T> (injected-class-name), which is why the definition repeats Counter<T> rather than Counter<typename T>.

QQuestionWhy does Counter<T>::count need a separate definition before

C++17?

ASolution

A declaration inside the class does not allocate storage. The out-of-class definition with template <class T> provides one definition per instantiation, and the linker merges duplicate instantiations across translation units.

Template instantiation

Implicit instantiation happens when you use a specialization. Explicit instantiation forces one and can live in a .cpp file:

// in a .cpp
template class Box<int>;          // define all members for Box<int>
extern template class Box<double>; // declare that another TU will provide it

extern template (C++11) avoids instantiating the same template in every TU, which shortens compile times.

Two-phase lookup is the rule that names not dependent on template parameters are looked up at definition time, and dependent names at instantiation time. That is why you sometimes need this-> or Base<T>:: to name members of a dependent base class:

template <class T>
struct D : Base<T> {
    void f() { this->member(); }   // 'member' is dependent, qualify it
};
QQuestionWhy can a template definition not go in a .cpp file while its

declaration is in a header?

ASolution

Implicit instantiation happens where the template is used, and that translation unit only sees the declaration. Without the body it cannot generate the code, and the linker reports an undefined symbol.

auto and decltype

auto deduces a type the way template argument deduction does: top-level const and references are dropped.

const int x = 5;
auto a = x;          // int, const dropped
auto& b = x;         // const int&, reference added explicitly
const auto& c = x;   // const int&

std::vector<int> v{1,2,3};
for (auto e : v) { }        // copies
for (auto& e : v) { }       // reference, can modify
for (const auto& e : v) { } // read-only reference

decltype reports the exact declared type, including references:

int x = 0;
decltype(x)  a = x;     // int
decltype((x)) b = x;    // int&, because (x) is an lvalue expression

The double parentheses matter: decltype(var) gives the declared type, while decltype((expr)) adds a reference for lvalues. This is how trailing return types and generic code preserve value categories.

template <class A, class B>
auto add(A a, B b) -> decltype(a + b) { return a + b; }   // C++11 form
// C++14: auto add(A a, B b) { return a + b; }
QQuestionWhat is the type of y in int x; auto y = x; and in

decltype(x) y = x;?

ASolution

int in both. auto strips the reference and const; decltype(x) gives the declared type. They differ when x is a reference or const.

Lambdas

A lambda is an anonymous function object. The capture list decides what state it carries.

int base = 10;
auto addBase = [base](int x) { return x + base; };   // captures a copy
auto addRef  = [&base](int x) { return x + base; };  // captures by reference

base = 20;
addBase(1);   // 11, captured the old value
addRef(1);    // 21, sees the new value

Captures:

Form Meaning
[] no captures
[=] capture everything used, by copy
[&] capture everything used, by reference
[x, &y] mixed
[x = std::move(p)] init-capture (C++14), moves into the closure
[this] capture the enclosing object’s this

By default operator() is const, so a by-value capture cannot be modified unless the lambda is mutable:

auto counter = [n = 0]() mutable { return ++n; };
counter();   // 1
counter();   // 2

A reference capture is a dangling hazard if the lambda outlives the variable:

std::function<int()> makeBad() {
    int x = 5;
    return [&x] { return x; };    // x dies at return
}

Generic lambdas use auto parameters, which makes operator() a template:

auto twice = [](auto x) { return x + x; };
twice(2);        // 4
twice(1.5);      // 3.0
QQuestionWhy can a [&] lambda stored in a std::function outlive its

captured variables?

ASolution

The closure stores a reference, not a copy. Nothing extends the lifetime of the local, so after the function returns the reference dangles.

constexpr and consteval

constexpr means “can be evaluated at compile time when the inputs are constant”. It does not force compile-time evaluation.

constexpr int square(int x) { return x * x; }

constexpr int a = square(5);     // computed at compile time
int n = 5;
int b = square(n);               // runtime call, same function

consteval (C++20) forces compile-time evaluation:

consteval int mustBeConst(int x) { return x * 2; }
int a = mustBeConst(3);          // ok
int n = 3;
int b = mustBeConst(n);          // error: n is not a constant expression

constinit (C++20) guarantees static initialization, avoiding the static initialization order problem:

constinit int global = compute();   // must be constant-initialized

Use constexpr for values and small functions, const for runtime immutability, and consteval only when a runtime call should be a compile error.

QQuestionDoes marking a function constexpr guarantee it runs at compile

time?

ASolution

No. It permits compile-time evaluation when the arguments are constant expressions. With runtime arguments it runs normally.

nullptr and enum class

nullptr is a distinct type (std::nullptr_t), which fixes overload resolution and template deduction problems that NULL (an integer 0) causes.

void f(int);
void f(char*);
f(nullptr);      // f(char*)
f(0);            // f(int)

enum class is a scoped enumeration: enumerators are inside the enum’s scope, and there is no implicit conversion to int.

enum class Color : uint8_t { Red, Green, Blue };
Color c = Color::Red;
int i = c;                     // error
int j = static_cast<int>(c);   // ok, 0

enum Old { A, B };             // unscoped: A and B leak into the enclosing scope
int k = A;                     // ok, implicit conversion

Specifying the underlying type fixes the size and the range, which matters for serialization and struct layout.

QQuestionWhy is enum class preferred over an unscoped enum?
ASolution

It keeps enumerator names scoped, prevents accidental integer conversions, and lets you choose the underlying type. Unscoped enums leak names and convert implicitly.

References, value categories, and move semantics

Every expression has a value category:

A move is a constructor or assignment that takes T&&. It binds to rvalues. std::move is only a cast:

template <class T>
std::remove_reference_t<T>&& move(T&& x) noexcept {
    return static_cast<std::remove_reference_t<T>&&>(x);
}

T&& in a template is a forwarding reference (universal reference), not an rvalue reference. It binds to both lvalues and rvalues, and std::forward<T> restores the original category:

template <class T>
void wrapper(T&& x) {
    target(std::forward<T>(x));   // lvalue stays lvalue, rvalue stays rvalue
}

Without std::forward, a named parameter x is always an lvalue inside the function, so the rvalue-ness is lost.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=2.3cm, minimum height=0.6cm, font=\scriptsize},
  a/.style={->, thick}]
  \node[b, fill=blue!12] (l) at (0,0) {lvalue};
  \node[b, fill=orange!15] (x) at (2.8,0) {xvalue};
  \node[b, fill=green!18] (p) at (5.6,0) {prvalue};
  \draw[a] (l) -- node[above, font=\scriptsize] {std::move} (x);
  \node[font=\scriptsize, anchor=north] at (0,-0.45) {has identity};
  \node[font=\scriptsize, anchor=north] at (2.8,-0.45) {expiring};
  \node[font=\scriptsize, anchor=north] at (5.6,-0.45) {temporary};
  \node[font=\scriptsize, anchor=north] at (2.8,-1.0) {glvalue = lvalue + xvalue; rvalue = xvalue + prvalue};
\end{tikzpicture}
QQuestionDoes std::move(x) move anything?
ASolution

No. It casts x to an rvalue reference. The actual move happens in the move constructor or move assignment that the cast selects.

C++17 evaluation order, and C++20 basics

C++17 fixed the order of several operators (details in Ch. 1): << and >> evaluate left to right, the right side of = before the left, subscript and member access left to right. Function arguments remain indeterminately sequenced, which makes f(i++, i++) unspecified rather than undefined.

C++20 highlights that show up in code:

template <class T>
concept Addable = requires(T a, T b) { a + b; };

template <Addable T>
T sum(T a, T b) { return a + b; }
#include <ranges>
auto evens = v | std::views::filter([](int x){ return x % 2 == 0; })
               | std::views::transform([](int x){ return x * x; });

For an OA, C++17 is the safe target; C++20 features are worth recognizing in questions, not worth depending on unless the judge says so.

QQuestionIs std::views::filter eager or lazy?
ASolution

Lazy. It builds a view that applies the predicate when iterated, so no elements are copied or processed until the range is consumed.

Bugs and edge cases

QQuestionWhy does std::move on a const std::string not move anything?
ASolution

It casts to const std::string&&, which cannot bind to std::string&&. The copy constructor accepts it instead, so the string is copied.

Next: Undefined Behavior and Tricky Expressions (C++ Core #6) — the section that maps most directly to OA output questions.