CodeBlanks Logo Icon CodeBlanks

Template specialization

Learn type-specific customization with template specialization.

Template specialization

Sometimes a template must behave differently for a specific type. Template specialization provides this. template <> struct Vector<bool> { ... }; is a specialized version for bool.

The empty angle brackets in template <> mean no type parameter remains; this is a full specialization. The general template template <typename T> struct Vector stays as is; the bool specialization overrides it. Vector<int> uses the general template, Vector<bool> uses the specialization.

Why specialize?

A bool vector can pack 8 bools into 1 byte. The general template cannot; it would allocate 1 byte per bool. Specialization provides an optimized version for specific types.

Full specialization is written with template <>. Partial specialization fixes some parameters: template <typename U> struct Vector<U*> is for pointer types. This lesson covers only full specialization. Specialization is used when performance or memory gains matter.

Practice Write the Vector<bool> specialization

First write the general template: template <typename T> struct Vector { T data; };. Then specialize for bool: template <> struct Vector<bool> { static const int bits = 8; };. In main write std::cout << Vector<bool>::bits << std::endl;.

Starter code

main.cpp
#include <iostream>

// write the general Vector<T> template
// write the Vector<bool> specialization: bits constant is 8

int main() {
    // print the bits constant
    return 0;
}

Sample solution

main.cpp
#include <iostream>

template <typename T>
struct Vector {
    T data;
};

template <>
struct Vector<bool> {
    static const int bits = 8;
};

int main() {
    std::cout << Vector<bool>::bits << std::endl;
    return 0;
}

Expected output

8

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the concept

Term Meaning
template <> Full specialization
Vector<bool> Special for bool
template <typename T> General template
Vector<int> General use

2 Complete the specialization declaration

Question
template <> struct Vector<____> { static const int bits = 8; };
Answer
template <> struct Vector<bool> { static const int bits = 8; };

Explanation: The Vector<bool> specialization is written for bool.

3 When is template specialization used?

main.cpp
// Belirli tür için özel davranış
  • When custom behavior is needed for a specific type Correct answer
  • Never
  • Always
  • Only when debugging

Explanation: Specialization is used when a specific type needs custom behavior.

All lessons in Intermediate