CodeTheRobot

C++ Intermediate · Lesson 18 of 27

Template specialization

Full and partial specialization, and overriding the generic behaviour for one type.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain template specialization 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

A specialization is a special version of a template for particular types. A full specialization (template <> ...) replaces the generic code for one exact type; a partial specialization (class templates only) handles a family such as all pointers, T*. Function templates cannot be partially specialized: use overloading instead.

Specialize when one type really needs different code, for example printing a bool as true/false. Do not specialize the standard library's templates other than the ones the standard allows (such as std::hash for your own type).

Guided lesson

Work through these steps

  1. 1.

    Read the template specialization 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

template <typename T>
// The generic template.
struct Describe { static const char* name() { return "unknown"; } };
// Default answer for every type.
template <>
// A full specialization follows, with no type parameter left.
struct Describe<int> { static const char* name() { return "int"; } };
// Used only when T is exactly int.
template <>
// Another full specialization.
struct Describe<double> { static const char* name() { return "double"; } };
// Used only when T is double.
template <typename T>
// A partial specialization is still a template.
struct Describe<T*> { static const char* name() { return "pointer"; } };
// Used for any pointer type.
std::cout << Describe<int>::name() << ' ' << Describe<char*>::name() << '\n';
// Prints: int pointer.

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 Template specialization. Expected result: int pointer unknown

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 <iostream>

template <typename T>
struct Describe {
  static const char* name() { return "unknown"; }
};

// TODO: specialize Describe for int (full) and for T* (partial)

int main() {
  std::cout << Describe<int>::name() << ' ' << Describe<char*>::name() << ' ' << Describe<float>::name() << '\n';
  return 0;
}

Expected output

int pointer unknown
Stuck? Show the full solution (try it yourself first)
#include <iostream>

template <typename T>
struct Describe {
  static const char* name() { return "unknown"; }
};

template <>
struct Describe<int> {
  static const char* name() { return "int"; }
};

template <typename T>
struct Describe<T*> {
  static const char* name() { return "pointer"; }
};

int main() {
  std::cout << Describe<int>::name() << ' ' << Describe<char*>::name() << ' ' << Describe<float>::name() << '\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 template struct UnitName<T> with specializations for Meters, Radians and NewtonMeters tag types. Add a partial specialization for std::vector<T> that appends '[]' to the inner name.

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.