Explicit specialization
Writing a separate definition for one set of template arguments with template<>: what can be specialized, where and when the specialization must be declared, how many template<> a member specialization needs, and why function templates are better overloaded than specialized.
Key points
- An explicit specialization
template<> ...is not a template but a concrete class, function or variable whose name happens to be writtenX<int>. Its definition is completely unrelated to the primary template. - The specialization must be declared before the first use that would cause implicit instantiation, and be visible in every translation unit that uses it; otherwise the program is ill-formed, no diagnostic required. The safest place is right after the primary template.
- Explicit specializations of function templates don't take part in overload resolution: the compiler first picks one of the primary templates, then checks whether it has been specialized. To customize behavior for a type, write an overload.
inline,constexpr, attributes and contracts aren't inherited from the template. A function template specialization in a header needs its owninline.- Defining a member of an explicitly specialized class takes no
template<>; only the enclosing templates that are still specializations each need onetemplate<>.
A replacement definition#
#include <cstdio>
template<class T> struct Traits { // primary template
static const char* name() { return "?"; }
};
template<> struct Traits<int> { // explicit specialization
static const char* name() { return "int"; }
static constexpr bool builtin = true; // the primary template has no such member
};
int main() {
std::printf("%s %s %d\n", Traits<double>::name(),
Traits<int>::name(), Traits<int>::builtin);
}The program prints ? int 1. Traits<double> is generated by the compiler from the primary template (the template as originally declared); this is called implicit instantiation ([temp.inst]). Traits<int> uses our hand-written definition instead, which is called an explicit specialization, colloquially a full specialization.
Explicit specializations differ from partial specializations ([temp.spec.partial]). A partial specialization such as Traits<T*> still has undetermined parameters and is still a template; an explicit specialization has all its arguments fixed and is a concrete entity. This determines most of the rules in this subclause:
- its definition is unrelated to the primary template, and its members can be completely different, such as the extra
builtinabove; - a specialized function is an ordinary function, isn't automatically
inline, and is subject to the ODR; - it must be declared before the compiler generates the same specialization from the primary template, or the same entity would have two definitions.
What can be specialized (¶1)#
¶1 The following entities can be explicitly specialized with a declaration introduced by template<>:
| ¶ | Entity | Example |
|---|---|---|
| 1.1 | function template | template<> void f<int>(int); |
| 1.2 | class template | template<> struct X<int> { }; |
| 1.3 | variable template | template<> constexpr int v<int> = 1; |
| 1.4 | member function of a class template | template<> void X<int>::mf(); |
| 1.5 | static data member of a class template | template<> int X<int>::s = 0; |
| 1.6 | member class of a class template | template<> struct X<int>::Inner { }; |
| 1.7 | member enumeration of a class template | template<> enum X<int>::E : int { a }; |
| 1.8 | member class template of a class or class template | template<> template<> struct X<int>::Y<char> { }; |
| 1.9 | member function template of a class or class template | template<> template<> void X<int>::g<char>(char); |
explicit-specialization:
template < > declarationA function template specialization can omit the template arguments, and the compiler deduces them from the function type:
template<class T> class Array { /* ... */ };
template<class T> void sort(Array<T>& v) { /* ... */ }
template<> void sort<int>(Array<int>&); // T = int written explicitly
template<> void sort(Array<char*>&); // T = char* deduced from the function typeFor the details of the deduction and how a choice is made among several candidate templates, see [temp.deduct.decl].
Declaration must precede use (¶7–¶9)#
template<class T> void sort(T*) { }
void f(int* p) { sort(p); }
// specialized after use
template<> void sort(int*) { } // errortemplate<class T> void sort(T*) { }
template<> void sort(int*) { }
void f(int* p) { sort(p); } // calls the specializationAt sort(p) on the left, the specialization hasn't been declared yet, so the compiler can only decide to generate sort<int> from the primary template. When a hand-written sort<int> appears afterwards, the same function has two different definitions. Clang 23 reports explicit specialization of 'sort<int>' after instantiation for the left side.
¶7 says: if a template, a member template or a member of a class template is explicitly specialized, then in every translation unit, the declaration of that specialization must be visible wherever there is a use that would cause implicit instantiation (in the standard's words, the declaration must be reachable from the use). Violating this requires no diagnostic; the program is ill-formed, IFNDR for short (ill-formed, no diagnostic required): the compiler may not report anything, and the generated program may do anything.
Across translation units, nobody can tell#
Within one translation unit the compiler can see the conflict, so Clang reports an error. When the specialization and the use are in two translation units, it can't:
template<class T> int size_of() { return sizeof(T); }
struct Foo { int a[4]; };#include "a.h"
int from_b() { return size_of<Foo>(); } // can't see the specialization#include "a.h"
#include <cstdio>
template<> int size_of<Foo>() { return -1; }
int from_b();
int main() { std::printf("%d %d\n", from_b(), size_of<Foo>()); }Clang 23 compiles and links this without a word. At -O0 it prints -1 -1; at -O2, 16 -1.
The reason lies at the symbol level. An explicit specialization and an implicit instantiation have the same mangled name and are the same symbol at link time. The size_of<Foo> implicitly instantiated in b.cpp is a weak definition, the explicit specialization in c.cpp is an ordinary strong definition, and the linker picks the strong one. But at -O2, b.cpp has already inlined the call to sizeof(Foo), and whatever the linker picks can't affect it.
Where to put specializations
Put an explicit specialization either in the same header as the primary template, or in the header of the type the specialization is for, right after the type's definition. Don't hide a specialization in some .cpp file and expect other translation units to pick it up.
A use that causes implicit instantiation isn't necessarily an explicit call. sizeof(X<int>), using X<int> as a base class or data member type, and indirect use while instantiating another template all count. So the closer the specialization is to the primary template, the better.
Declared but not defined#
¶7 has two more sentences:
- If the program doesn't provide a definition for an explicit specialization, and it is used in a way that would cause implicit instantiation, or it is a virtual member function, the program is IFNDR. In practice this usually shows up as a link error.
- An explicit specialization that is declared but not defined is never implicitly instantiated.
Note 2 under ¶9 follows from this: a class template specialization that is declared but not defined is an incomplete class and can be used like any other incomplete class.
template<class T> class X { }; // the primary template is defined
template<> class X<int>; // only declares the specialization
X<int>* p; // OK: pointer to an incomplete class
X<int> x; // error: X<int> is an incomplete typeEven though the primary template is defined, X<int> isn't generated from it. This can be used to forbid a particular argument, though since C++20 constraints ([temp.constr]) usually express it more clearly.
Member enumerations: is it too late to specialize?
The second half of Example 4 in the standard:
template<class T> struct A {
enum E : T;
enum class S : T;
};
template<> enum A<int>::E : int { eint }; // OK
template<> enum class A<int>::S : int { sint }; // OK
template<class T> enum A<T>::E : T { eT };
template<class T> enum class A<T>::S : T { sT };
template<> enum A<char>::E : char { echar }; // error
template<> enum class A<char>::S : char { schar }; // OKWriting the name A<char>::E first requires implicitly instantiating A<char> to look up the member E. When the class is instantiated, the definition of an unscoped enumeration is instantiated with it ([temp.inst]/3); at that point the out-of-class definition { eT } is already visible, so specializing E afterwards is too late. For the scoped enumeration S only the declaration is instantiated, so there's still time. The two specializations of A<int> come before { eT }, when E has no usable definition yet, so there's no conflict. Clang 23 reports explicit specialization of 'E' after instantiation for the A<char>::E line.
¶8 lists a long series of entities (all kinds of templates, all kinds of members) and says that the placement of explicit and partial specialization declarations for them relative to points of instantiation determines whether the program is well-formed. The paragraph ends with a rhyming five-line limerick whose gist is that when writing a specialization you should be careful about where you put it, or getting it to compile will be a trial. It introduces no new rules; it is just a reminder of the consequences of ¶7 and [temp.point].
Function template specializations don't take part in overloading (¶11)#
#include <stdio.h>
template<class T> void f(T) { puts("a"); }
template<> void f(int*) { puts("c"); }
template<class T> void f(T*) { puts("b"); }
int main() { int* p{}; f(p); } // prints b#include <stdio.h>
template<class T> void f(T) { puts("a"); }
template<class T> void f(T*) { puts("b"); }
template<> void f(int*) { puts("c"); }
int main() { int* p{}; f(p); } // prints cThe two programs differ only in where the specialization c is, yet the results differ. There are two steps to the explanation.
- Which template a specialization belongs to is decided by the templates visible when it is declared ([temp.deduct.decl]). On the left, when
cis declared onlyf(T)is visible, so it isf(T)'s specializationf<int*>. On the right both templates match,f(T*)is more specialized, so it isf(T*)'s specializationf<int>. - Overload resolution happens only among the primary templates ([temp.over]). The candidates for
f(p)aref<int*>deduced fromf(T)andf<int>deduced fromf(T*), and partial ordering picksf(T*). Only after that is it checked whetherf(T*)'sf<int>has been explicitly specialized. On the left it hasn't, sobis printed; on the right it has, socis printed.
So an explicitly specialized function never takes part in the selection; it only replaces the body of the specialization that was already selected. This makes the code's behavior depend on declaration order, which is hard to reason about.
¶11 also specifies that an ordinary function with the same name as a template and a type that happens to equal some specialization of the template is not an explicit specialization but an independent non-template function that overloads with the template ([temp.fct]):
#include <cstdio>
template<class T> void k(T) { std::puts("primary"); }
void k(int) { std::puts("plain overload"); } // ordinary function
template<> void k(int) { std::puts("specialization"); } // specialization of k<int>
int main() {
k(1); // plain overload: the non-template wins when equally good
k<>(1); // specialization: <> considers only templates
k<int>(1); // specialization
}k(1) selects the ordinary function, by [over.match.best] ¶2.4: when two candidates are equally good, the non-template function wins.
Two practical recommendations follow:
- To customize a function template's behavior for a type, write an ordinary overload (a non-template function or another function template), not an explicit specialization.
- When you really need specialization semantics (for example, the function template is a library customization point), have the function template forward to a static member function of a class template, and specialize or partially specialize that class template.
inline, constexpr, attributes and contracts aren't inherited (¶12)#
¶12 Whether an explicit specialization of a function template or variable template is inline, constexpr, constinit or consteval is determined by the specialization's own declaration, independent of the template. Attributes on the template declaration and C++26 function contract specifiers (pre, post) have no effect on explicit specializations either.
template<class T> void f(T) { /* ... */ }
template<class T> inline T g(T) { /* ... */ }
template<> inline void f<>(int) { /* ... */ } // OK: inline
template<> int g<>(int) { /* ... */ } // OK: not inline
template<typename> [[noreturn]] void h([[maybe_unused]] int i);
template<> void h<int>(int i) {
// [[noreturn]] isn't inherited: implementations shouldn't warn that the function returns
// [[maybe_unused]] isn't inherited either: implementations may warn that i is unused
}A consequence of constexpr not being inherited:
template<class T> constexpr int k(T) { return 1; }
template<> int k(int) { return 2; } // not constexpr
static_assert(k('a') == 1); // OK: k<char> generated from the primary template
static_assert(k(0) == 2); // error: k<int> isn't constexprThe rule exists because a specialization has its own body. constexpr is a promise about the function body, and the primary template's body being constant-evaluable says nothing about the specialization's; inline decides whether a definition may be repeated in several translation units, and only the person writing the definition knows where it goes. The language has no syntax for removing these specifiers, so the only option is to make them not inherited.
Function template specializations in headers
A function template and its implicit instantiations may be defined repeatedly in several translation units ([basic.def.odr]), but an explicit specialization is an ordinary function. Put template<> void f(int) { ... } in a header included by two .cpp files, and the same non-inline function is defined twice, giving a duplicate symbol at link time. Write template<> inline void f(int) { ... }, or put only the declaration in the header and define it in one .cpp file. The same goes for variable template specializations: use inline or constexpr (a constexpr variable is implicitly inline).
Specializing members of class templates (¶5–¶6, ¶14–¶17)#
Replacing just one member (¶5, ¶14)#
#include <cstdio>
template<class T> struct Printer {
void print(T) { std::puts("generic"); }
void hello() { std::puts("hello"); }
};
template<> void Printer<bool>::print(bool v) {
std::puts(v ? "true" : "false");
}
int main() {
Printer<bool> p;
p.print(true); // true: the explicitly specialized member
p.hello(); // hello: still generated from the template
}¶5 A member function, member function template, member class, member enumeration, member class template, static data member or static data member template of a class template can be explicitly specialized on its own for an implicitly instantiated class specialization. The class template's definition must be visible. Printer<bool> itself is still generated from the template; only print is replaced with the hand-written version. If such a specialization names an implicitly-declared special member function (for example a default constructor that was never declared), the program is ill-formed.
¶14 A member can be specialized even if it already has a body in the class template definition. A member template specialization can specialize just the enclosing class, or the member template too:
template<class T> struct A {
void f(T);
template<class X1> void g1(T, X1);
template<class X2> void g2(T, X2);
void h(T) { }
};
template<> void A<int>::f(int); // specializes a member function
template<class T> template<class X1>
void A<T>::g1(T, X1) { } // out-of-class definition of a member template (not a specialization)
template<> template<class X1>
void A<int>::g1(int, X1); // specializes only A<int>; g1 is still a template
template<> template<>
void A<int>::g1(int, char); // specializes both: X1 deduced as char
template<> template<>
void A<int>::g2<char>(int, char); // X2 explicitly specified as char
template<> void A<int>::h(int) { } // can specialize even with an in-class definitionThe third declaration illustrates a point from ¶17: a member template of an unspecialized class template that still has its own parameters after specialization is itself still a template.
How many template<> to write (¶6, ¶15–¶16)#
¶6 Members of an explicitly specialized class are not generated from the class template's member declarations; every member that is used must be defined by you. The specialized class's definition is unrelated to the generated specialization, so its members are defined just like members of an ordinary class, without template<>:
template<class T> struct A {
struct B { };
template<class U> struct C { };
};
template<> struct A<int> { // explicitly specialized class
void f(int);
};
void h() {
A<int> a;
a.f(16); // A<int>::f must be defined somewhere
}
void A<int>::f(int) { } // no template<>: A<int> is an ordinary class
template<> struct A<char>::B { // specialized member class; A<char> generated from the template
void f();
};
void A<char>::B::f() { } // none here either: A<char>::B is an ordinary class
template<> template<class U>
struct A<char>::C { // a specialized member class template is still a class template
void f();
};
template<> // needed: the enclosing A<char> is a specialization
template<class U> void A<char>::C<U>::f() { }
template<> struct A<short>::B { void f(); };
template<> void A<short>::B::f() { } // error: template<> not allowed
template<> template<class U> struct A<short>::C { void f(); };
template<class U> void A<short>::C<U>::f() { } // error: template<> missingOne way to remember it: once specialized, A<int> is an ordinary class and A<int>::f an ordinary member function, defined like a member of struct Foo without any template. A<char>::C<U> is still a template, so defining its members requires both the enclosing specialization (template<>) and its own parameters (template<class U>).
¶15 A member can be nested in several levels of class templates. When specializing such a member, each enclosing class template that is explicitly specialized needs its own template<>:
template<class T1> class A {
template<class T2> class B {
void mf();
};
};
template<> template<> class A<int>::B<double>;
template<> template<> void A<char>::B<char>::mf();¶16 In a declaration at namespace scope, only some levels may be specialized while the others remain unspecialized, with template<parameter-list> in place of that level's template<>; the kinds of parameters must match the primary template's definition. But a member class template can't be specialized when its enclosing class template isn't:
template<class T1> class A {
template<class T2> class B {
template<class T3> void mf1(T3);
void mf2();
};
};
template<> template<class X>
class A<int>::B { // specializes A<int>; B is still a template
template<class T> void mf1(T);
};
template<> template<> template<class T>
void A<int>::B<double>::mf1(T t) { } // specializes A<int> and B<double>; mf1 is still a template
template<class Y> template<>
void A<Y>::B<double>::mf2() { } // error: B<double> is specialized but the enclosing A isn'tThe last line is forbidden because the Y in A<Y> is unknown, and some explicit specialization of A might change the member B beyond recognition or remove it altogether, so specializing A<Y>::B<double> for all Y makes no sense.
Static data members: a definition only with an initializer (¶13)#
¶13 An explicit specialization of a static data member of a template, or of a static data member template, is a definition if it has an initializer, and otherwise only a declaration:
struct Q { Q() {} };
template<class T> struct X { static Q x; };
template<> Q X<int>::x; // declaration, not a definition
template<> Q X<int>::x (); // error: declares a function
template<> Q X<int>::x = Q(); // definition
template<> Q X<char>::x{}; // definition: braced initializerThis differs from static data members of ordinary classes, where Q S::x; outside the class is a definition. Explicit specializations need a way to merely declare that a specialization exists (to put in a header), so the form without an initializer was made a declaration. For default initialization, Note 4 suggests a functional cast = Q(); since C++11 {} works as well.
Other restrictions (¶2–¶4, ¶10, ¶18–¶19)#
¶2 An explicit specialization can't be an export declaration. In a module, specializations are reachable along with the primary template and don't need to be exported separately. An explicit specialization also can't have a storage class specifier other than thread_local: template<> static void f<int>(int); is ill-formed, since linkage is determined by the primary template. Clang 23 gives only a warning for this (-Wexplicit-specialization-storage-class), which satisfies the requirement of at least one diagnostic.
¶3 An explicit specialization may be declared in any scope in which the primary template may be defined ([dcl.meaning], [class.mem], [temp.mem]), including class scope:
struct S {
template<class T> int g(T) { return 0; }
template<> int g(int) { return 1; } // specializing a member function template inside the class
};Earlier standards required explicit specializations to appear only at namespace scope; CWG727 relaxed this to today's rule. Clang 23 accepts the code above.
¶4 An explicit specialization doesn't introduce a new name. The template being specialized must at least be declared (not necessarily defined) first; when specializing a member template, the definition of the enclosing class or class template must be visible:
template<> class X<int> { /* ... */ }; // error: X is not a template yet
template<class T> class X;
template<> class X<char*> { /* ... */ }; // OK¶10 Note 3 reminds us that when specializing a constrained template, the template arguments must satisfy the template's associated constraints ([temp.constr.decl]).
¶18 An explicit specialization declaration can't be a friend declaration. template<> friend struct S<int>; is ill-formed. A friend declaration can name an existing function template specialization, as in friend void f<>(int);, but that refers to a specialization rather than declaring one.
¶19 Default function arguments can't be specified in the declaration or definition of three kinds of explicit specialization: an explicit specialization of a function template (¶19.1), of a member function template (¶19.2), and of a member function of a class template where the class specialization is implicitly instantiated (¶19.3).
template<class T> void f(T) { }
template<> void f(char = 'a') { } // error: a specialization can't have default argumentsIn a function call, default arguments are taken from the declaration of the template chosen by overload resolution, and specializations are only considered after the template is chosen. If a specialization could have its own default arguments, whether a call like f() is valid would depend on whether the specialization is visible. Note 5 points out that member functions of an explicitly specialized class (like A<int>::f above) can have default arguments, because they are ordinary member functions of an ordinary class.
Names in the template arguments and function declarator of an explicit specialization declaration aren't access-checked, so private member types of a class can be written directly ([temp.spec]/6, C++20's P0692R1).
Common misconceptions#
Specializing std::swap
Declaring an explicit specialization of a standard library function template in std is undefined behavior ([namespace.std]/1); only standard library class templates (like std::hash and std::formatter) may be specialized, under certain conditions ([namespace.std]/2). So template<> void std::swap(MyType&, MyType&) is wrong; write a swap overload in MyType's namespace instead, and let ADL find it.
Specializing a function template changes the result of overload resolution
It doesn't. A specialization only replaces the body of the specialization that was selected; it can't make a template that wouldn't be selected win. See the comparison under ¶11 above. To influence the selection, write an overload.
Questions#
Question
What does the following program print?
#include <cstdio>
template<class T> void f(T) { std::puts("a"); }
template<class T> void f(T*) { std::puts("b"); }
template<> void f<int*>(int*) { std::puts("c"); }
int main() { int x; f(&x); }
Answer
It prints b. The specialization explicitly says f<int*>, i.e. T = int*: substituted into f(T) it gives f(int*), into f(T*) it gives f(int**), and only the former matches the declared type, so it specializes f(T). For the call f(&x), partial ordering picks the more specialized f(T*) (T = int), and f(T*)'s f<int> hasn't been specialized, so b is printed. Only template<> void f<int>(int*), or template<> void f(int*) without template arguments (both templates visible, partial ordering picks f(T*)), would print c. With Clang 23 the program prints b.
History#
History
- Explicit specialization existed in C++98, and the limerick in ¶8 has been kept since then.
- C++14 added variable templates, and with them explicit specializations of variable templates.
- CWG727 allowed explicit specialization at class scope.
- C++20's P0692R1 exempted names in specialization declarations from access checking;
constinitandconstevaljoined the list of specifiers that aren't inherited. - C++26 specifies that function contract specifiers aren't inherited from the template.