Post

Template Specialization

Template Specialization

Template Specialization


Prerequisites

1
- Template

1. What is Template Specialization

Template specialization allows you to provide a custom implementation of a template for specific types.

β€œWhat if I want different behavior for certain types?”

Use it when:

  • behavior must change for specific types
  • performance is critical (compile-time dispatch)
  • writing generic libraries or frameworks

Basic Template

1
2
3
4
5
template<typename T>
void print(T value)
{
    std::cout << value << "\n";
}

πŸ‘‰ This works for most types.

Full Specialization

Provide a completely different implementation for a specific type.

1
2
3
4
5
template<>
void print<const char*>(const char* value)
{
    std::cout << "C-string: " << value << "\n";
}

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

template<typename T>
void print(T value)
{
    std::cout << value << "\n";
}

template<>
void print<const char*>(const char* value)
{
    std::cout << "Specialized: " << value << "\n";
}

int main()
{
    print(10);            // generic
    print("hello");       // specialized
}

2. Why Specialization is Needed

Example problem:

1
2
3
4
5
template<typename T>
bool isEqual(T a, T b)
{
    return a == b;
}

Works fine for most types, but:

1
2
const char* a = "hello";
const char* b = "hello";

This compares addresses, not content

Fix with Specialization

1
2
3
4
5
6
7
#include <cstring>

template<>
bool isEqual<const char*>(const char* a, const char* b)
{
    return std::strcmp(a, b) == 0;
}

3. Full vs Partial Specialization

Full Specialization

1
2
3
4
5
template<>
class MyClass<int>
{
    // specific implementation
};

Completely replaces template for int

Partial Specialization (Only for Class Templates)

1
2
3
4
5
template<typename T>
class MyClass<T*>
{
    // pointer-specific implementation
};

Applies to all pointer types

❗ Important Rule

Function templates cannot be partially specialized

Instead, use:

  • overloading

❌ Trying partial specialization on functions

1
2
template<typename T>
void func<T*>(T* value);  // ❌ not allowed
This post is licensed under CC BY 4.0 by the author.