Conceptadvanced
Specialization
Also called template specialization, explicit specialization, full specialization, partial specialization, partial template specialization, impl specialization, trait specialization, overlapping implementations.
Specialization gives generic code a special version for some type arguments, such as std::vector<bool> in C++, and a rule picks the most specific version that matches.
- Applies to
- core-languages
Idea
A generic function or type uses one piece of code for every type argument. Sometimes one type argument needs different code: a faster way for integers, a smaller layout for bool, or a different text for strings. Specialization lets the program write that version beside the generic one. When the program uses the template with that type, the compiler picks the special version.
#include <iostream>
#include <string>
template <typename T>
std::string describe(const T&) {
return "some value";
}
// A full specialization for int.
template <>
std::string describe<int>(const int& x) {
return "the int " + std::to_string(x);
}
int main() {
std::cout << describe(2.5) << "\n";
std::cout << describe(7) << "\n";
}
some value
the int 7
The primary template works for every type. The line template <> starts a full specialization: a version of describe for int only. The call with 2.5 uses the primary template, and the call with 7 uses the specialization.
How it works
Full specialization. In C++, explicit specialization "Allows customizing the template code for a given set of template arguments."1 The program gives every template argument, as in template <> class KeyValuePair<int, string>2. "Specialization must be declared before the first use that would cause implicit instantiation"1.
Partial specialization. A class template can also be specialized for a group of type arguments. Partial specialization customizes class and variable templates "for a given category of template arguments"3, such as every pointer type T* or every pair whose two types are the same. It "allows the programmer to specialize only some arguments of a class template, as opposed to explicit full specialization, where all the template arguments are provided"2. In C++, "partial specializations are only allowed for class templates and variable templates"4, so a function template uses overloading instead.
Choosing a version. More than one version can match. "If more than one specialization matches, partial order rules are used to determine which specialization is more specialized. The most specialized specialization is used, if it is unique"3. Informally, "A is more specialized than B" when A accepts a subset of the types that B accepts3. If no specialization matches, the compiler uses the primary template3.
A known case. The C++ standard library has std::vector<bool>, which "is a possibly space-efficient specialization of std::vector for the type bool"5. It can store each element as one bit, so it "Does not necessarily store its elements as a contiguous array"5.
Specialization in Rust. Rust does not let two trait impl blocks apply to one type. "A trait implementation is considered incoherent if either the orphan rules check fails or there are overlapping implementation instances."6 RFC 1210 proposes a design for specialization, "which permits multiple impl blocks to apply to the same type/trait"7, when one of the blocks is clearly more specific than the other. The feature is in the Unstable Book, with the tracking issue #318448. A program that uses an unstable feature "must use a flag"9, so stable Rust does not have specialization.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Absent | Python has no generic code that the compiler specializes. Type parameters are for static checkers only. Alternative: Functools.singledispatch, which picks a function by the type of the first argument when the program runs. |
| C++ | Native | |
| Java | Absent | Java erases type arguments, so a generic class or method has one version for every type argument. Alternative: Overloaded methods for the types that need special code. |
| C | Does not apply | C has no templates or generics to specialize. |
| C# | Absent | C# has no specialization of generic types or methods. Alternative: A test of typeof(T) inside the generic method, or overloads for the types that need special code. |
| JavaScript | Does not apply | JavaScript has no type parameters, so there is no generic code to specialize. |
| TypeScript | Absent | TypeScript removes its types before the program runs, so the code cannot depend on a type argument. Alternative: Overload signatures with one implementation that tests its arguments. |
| Go | Absent | Go has no specialization of generic functions or types. Alternative: A type switch on a value of the type parameter inside the generic function. |
| Rust | Absent | |
| Kotlin | Absent | Kotlin erases type arguments on the JVM, as Java does. Alternative: Overloaded functions, or a when expression on the type of a value. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query has no type parameters. |
| Bash | Does not apply | Bash has no types for its values. |
| PowerShell | Does not apply | A PowerShell script cannot declare its own generic code. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no types of values. |
| CSS | Does not apply | CSS has no types in this sense. |
| Regular expressions | Does not apply | A regular expression has no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | absent | no generic code to specialize; functools.singledispatch picks a function by the type of the argument when the program runs |
| JavaScript | n/a | the language has no type parameters |
| TypeScript | absent | types are removed before the program runs; overload signatures and type tests are the usual way |
| Java | absent | generics are erased, so a version for one type argument is not possible; overloads take its place |
| Kotlin | absent | generics are erased on the JVM; overloads and when on the type take its place |
| C# | absent | no specialization; a generic method can test typeof(T) |
| Go | absent | no specialization; a type switch inside a generic function takes its place |
| Rust | absent | specialization is an unstable feature; stable Rust has separate impls for separate types |
| C | n/a | the language has no templates |
| C++ | native | full specialization of templates and partial specialization of class and variable templates |
| Bash | n/a | the language has no types |
| PowerShell | n/a | a script cannot declare its own generic code |
| SQL | n/a | a query has no type parameters |
| Regex | n/a | a pattern has no types |
| HTML | n/a | HTML has no types |
| CSS | n/a | CSS has no types of this kind |
C++ is the only one of these languages with specialization as a stable feature. The others use overloads, a test on the type, or a separate implementation for each type.
The example files show C++ full and partial specialization, and the Rust error for two overlapping impl blocks, with the stable way to give each type its own code.
#include <iostream>
#include <vector>
// The primary template.
template <typename T, typename U>
struct Pair {
static const char* kind() { return "two types"; }
};
// A partial specialization: both types are the same.
template <typename T>
struct Pair<T, T> {
static const char* kind() { return "one type twice"; }
};
// A partial specialization: the second type is a pointer.
template <typename T, typename U>
struct Pair<T, U*> {
static const char* kind() { return "second is a pointer"; }
};
// A full specialization.
template <>
struct Pair<int, double> {
static const char* kind() { return "int and double"; }
};
int main() {
std::cout << Pair<char, long>::kind() << "\n";
std::cout << Pair<long, long>::kind() << "\n";
std::cout << Pair<char, int*>::kind() << "\n";
std::cout << Pair<int, double>::kind() << "\n";
std::vector<bool> bits{true, false};
auto ref = bits[0]; // a proxy object, not a bool&
ref = false;
std::cout << std::boolalpha << bits[0] << "\n";
}
two types
one type twice
second is a pointer
int and double
false
- Verdict: native.
Pair<T, T>andPair<T, U*>are partial specializations, andPair<int, double>is a full specialization. The compiler picks the most specialized version that matches.bits[0]gives astd::vector<bool>::reference, soautomakes a proxy, and writing to it changes the vector.
This code does not compile, on purpose.
trait Describe {
fn describe(&self) -> String;
}
// A blanket impl for every type that can be printed.
impl<T: std::fmt::Debug> Describe for T {
fn describe(&self) -> String {
format!("some value {:?}", self)
}
}
// A special impl for i32 overlaps the blanket impl.
impl Describe for i32 {
fn describe(&self) -> String {
format!("the int {}", self)
}
}
fn main() {
println!("{}", 7.describe());
}
trait Describe {
fn describe(&self) -> String;
}
// Stable Rust: one impl for each type, with no overlap.
impl Describe for f64 {
fn describe(&self) -> String {
format!("some value {}", self)
}
}
impl Describe for i32 {
fn describe(&self) -> String {
format!("the int {}", self)
}
}
fn main() {
println!("{}", 2.5.describe());
println!("{}", 7.describe());
}
some value 2.5
the int 7
- Verdict: absent. The first program does not compile, because the blanket impl for every
Debugtype and the impl fori32overlap. Specialization would let the more specific impl win, but it is an unstable feature. Stable Rust gives each type its own impl.
Variations and related ideas
- Overloading. A function template cannot be partially specialized, but an overload with a more specific parameter, such as
f(T*), does the same work. See overloading. - Specialization for speed. Part of the motivation of RFC 1210 is performance: "specialized impls can provide custom high-performance code for particular, concrete cases of an abstraction"7.
- Choosing by a test. A language without specialization can test the type argument inside the generic code, for example with
typeof(T)in C# or a type switch in Go. The test runs in the generic code, so the compiler cannot reject a missing case.
Pitfalls
- A specialization that changes the behaviour. A specialization can do something that the primary template does not.
std::vector<bool>does not store its elements as an array ofbool5, and its elements are reached through a proxy class,std::vector<bool>::reference5. Code that takes abool&or abool*to an element works for other vectors and does not compile forstd::vector<bool>. - A specialization declared too late. The specialization must come before the first use that instantiates the template, in each translation unit1. Put it in the same header as the primary template.
- Two specializations that match equally. If no matching specialization is more specialized than the others, "the program cannot be compiled"3. Add a specialization for the overlap.
- Specialization based on lifetimes in Rust. RFC 1210 says that the compiler "cannot, and should not allow specialization based on lifetimes"7, because lifetimes are erased before the code is made.
History
Partial specialization was not in every C++ compiler: "Some older compilers allow one only to specialize either all or none of the template's parameters"2. For Rust, RFC 1210 has the start date 2015-06-177, and the feature has a page in the Unstable Book, with its tracking issue8.
References
- Explicit (full) template specialization, C++ reference, cppreference.com, Introduction
- Partial template specialization, Wikipedia, Introduction; Templates and specialization
- Partial template specialization, C++ reference, cppreference.com, Introduction; Partial ordering
- Templates, C++ reference, cppreference.com, Introduction
- std::vector<bool>, C++ reference, cppreference.com, Introduction
- Implementations, The Rust Reference, Trait implementation coherence
- RFC 1210, impl specialization, The Rust RFC Book, Summary; Motivation
- specialization, The Rust Unstable Book, Whole page
- The Unstable Book, Introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XK6JZT Edit this page History Report an error Markdown