CKTIS / C++
Full and partial template specialization
Template specialization supplies a different definition for specific arguments or a family of arguments. Learn the difference between full specialization with template<> and partial specialization, such as for T*, and the restrictions on function templates.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
template<class T> struct Kind { /* primary template */ };
template<> struct Kind<int> { /* full specialization */ };
template<class T> struct Kind<T*> { /* partial specialization */ };The primary template provides the general definition. A full specialization supplies a definition for one concrete set of arguments; in the simple case, it starts with template<>. A partial specialization remains a template: it describes a family of matching arguments, such as Kind<T*> for pointer types. It does not simply mean omitting some arguments.
Class and variable templates can be partially specialized, but function templates cannot. Function templates allow full specialization; for families of arguments, use overloads, optionally with constraints. Specialization is not explicit instantiation: template struct Kind<double>; requests instantiation of an existing definition rather than supplying a new one.
In the example, Kind<double> uses the primary template, Kind<double*> matches the partial specialization, and Kind<int*> uses the full specialization. When several partial specializations match, there must be a unique most specialized one; otherwise the use is ambiguous. Class specialization definitions do not automatically acquire members from the primary template.
Declare the primary template before its specializations. Relevant specialization declarations must be reachable before uses that trigger instantiation, in every applicable translation unit; violations of these rules do not always require a diagnostic. The example is intended for local checking with -std=c++23. The sources are a working draft, not a frozen C++23 edition.
Reference identifiers covered by this entry: full / partial specialization.
Examples
#include <iostream>
template<class T>
struct Kind {
static constexpr const char* name = "primary";
};
template<class T>
struct Kind<T*> {
static constexpr const char* name = "partial";
};
template<>
struct Kind<int*> {
static constexpr const char* name = "full";
};
int main() {
static_assert(Kind<double>::name[0] == 'p');
static_assert(Kind<double*>::name[0] == 'p');
static_assert(Kind<int*>::name[0] == 'f');
std::cout << Kind<double>::name << '\n'
<< Kind<double*>::name << '\n'
<< Kind<int*>::name << '\n';
}
Result
primary partial full
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.