capypad
0 day streak
cpp / intermediate
Snippet

Template Specialization

Template Specialization allows you to define a custom implementation of a template for a specific data type, overriding the generic version.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
template <typename T>
class Formatter {
public:
void print(T val) { /* Default logic */ }
};
 
template <>
class Formatter<bool> {
public:
void print(bool val) {
std::cout << (val ? "Yes" : "No");
}
};
Breakdown
1
template <>
Indicates that this is a full specialization of a previously defined template.
2
class Formatter<bool>
Specifies that this particular version of the class is only for the bool type.