0Pricing
C++ Academy · Lesson

Function and Class Templates Revisited

Write generic functions and classes with proper template syntax.

Why Templates?

Templates let you write code once and have the compiler generate specific versions for each type used. Cornerstone of generic programming.

Function Template Syntax

Declare type parameters with template <typename T>. Use T in the function signature.

template <typename T>
T max_of(T a, T b) {
    return (a > b) ? a : b;
}

std::cout << max_of(3, 7);          // int
std::cout << max_of(2.5, 1.5);      // double

All lessons in this course

  1. Function and Class Templates Revisited
  2. Template Specialization Partial and Full
  3. Variadic Templates and Parameter Packs
  4. constexpr Functions and if constexpr
← Back to C++ Academy