0Pricing
C++ Academy · Lesson

Full Specialization

Customize templates for a type.

Recap: Templates

A template lets one piece of code work for many types. The compiler generates a concrete version for each type you use.

  • The general form handles every type.
  • Sometimes one type needs special treatment.
#include <iostream>

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

int main() {
    std::cout << maxOf(3, 9) << ' ' << maxOf(2.5, 1.5) << '\n';
    return 0;
}

What Is Full Specialization?

Full specialization provides a completely separate implementation for one specific type, overriding the general template for that type only.

#include <iostream>

template <typename T>
void describe(T) { std::cout << "some type\n"; }

template <>
void describe(int) { std::cout << "an int\n"; }

int main() {
    describe(3.14);
    describe(42);
    return 0;
}

All lessons in this course

  1. Full Specialization
  2. Partial Specialization
  3. SFINAE
  4. enable_if Patterns
← Back to C++ Academy