CodeTheRobot

C++ Intermediate · Lesson 20 of 27

Generic programming patterns

Policies, tag dispatch, CRTP and writing small generic algorithms.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain generic programming patterns in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

Generic code is written against the operations a type must support, not against one specific type. Common patterns are tag dispatch (choose an implementation from a small tag type), policy classes (pass behaviour as a template parameter) and CRTP (a class derives from a template of itself to get static polymorphism without virtual calls).

Keep generic code simple: write the concrete version first, make it generic only when a second type appears, and test it with at least two different types. A small, well-named template beats a clever one.

Guided lesson

Work through these steps

  1. 1.

    Read the generic programming patterns example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

struct Fast {}; struct Safe {};
// Two empty tag types used only to select code.
template <typename T>
// Fast overload.
T scale(T v, T f, Fast) { return v * f; }
// The tag says: no checks, just multiply.
template <typename T>
// Safe overload.
T scale(T v, T f, Safe) { return f < 0 ? T{} : v * f; }
// The tag says: refuse negative factors.
template <typename Derived>
// CRTP base: knows the derived type at compile time.
struct Shape { double area_twice() const { return 2 * static_cast<const Derived*>(this)->area(); } };
// Calls Derived::area() without a virtual function.
struct Square : Shape<Square> { double side{2}; double area() const { return side * side; } };
// Derive from Shape of itself: the CRTP pattern.
std::cout << scale(3.0, 2.0, Safe{}) << ' ' << Square{}.area_twice() << '\n';
// Prints: 6 8.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Values in memory

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

motor speed030x1070x1410x1890x1c40x2060x2420x2880x2c*p += 10VALUES IN MEMORY

Demo for Generic programming patterns. Expected result: 2.5 1.5

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <array>
#include <iostream>
#include <numeric>
#include <vector>

// TODO: write template mean(const C& c): sum with accumulate from c.begin() to c.end(), divide by c.size()

int main() {
  std::cout << mean(std::vector<int>{1, 2, 3, 4}) << '\n';
  std::cout << mean(std::array<double, 2>{1.0, 2.0}) << '\n';
  return 0;
}

Expected output

2.5
1.5
Stuck? Show the full solution (try it yourself first)
#include <array>
#include <iostream>
#include <numeric>
#include <vector>

template <typename C>
double mean(const C& c) {
  return std::accumulate(c.begin(), c.end(), 0.0) / c.size();
}

int main() {
  std::cout << mean(std::vector<int>{1, 2, 3, 4}) << '\n';
  std::cout << mean(std::array<double, 2>{1.0, 2.0}) << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Write a generic mean() that works on any container with begin()/end() of numbers. Add a policy parameter that chooses between plain mean and trimmed mean, and test it with vector<int>, array<double,4> and list<float>.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.