The "template<>" prefix tells the compiler that what follows is a specialization of a template. The type for the specialization must appear in angle brackets immediately following the function name, as it normally would in an explicitly-specified call. Note that we
Explicit specializations tend to be more useful for class templates than for function templates. When you provide a full specialization for a class template, though, you may need to implement all the member functions. This is because you are providing a separate class, and client code may expect the complete interface to be implemented.
The standard library has an explicit specialization for vector when it is used to hold objects of type bool. As you saw earlier in this chapter, the declaration for the primary vector class template is:
template
class vector {…};
To specialize for objects of type bool, you could declare an explicit specialization as follows:
template <>
class vector< bool, allocator
Again, this is quickly recognized as a full, explicit specialization because of the template<> prefix and because all the primary template’s parameters are satisfied by the argument list appended to the class name. The purpose for vector
It turns out that vector
Partial Specialization
Class templates can also be partially specialized, meaning that at least one of the template parameters is left "open" in some way in the specialization. This is actually what vector
template
class vector
You can recognize a partial specialization because non-empty parameter lists appear in angle brackets both after the template keyword (the unspecified parameters) and after the class (the specified arguments). Because of the way vector
Partial ordering of class templates
The rules that determine which template is selected for instantiation are similar to the partial ordering for function templates—the "most specialized" template is selected. An illustration follows. (The string in each f( ) member function below explains the role of each template definition.).
//: C05:PartialOrder2.cpp
// Reveals partial ordering of class templates
#include
using namespace std;
template
public:
void f() {
cout << "Primary Template\n";
}
};
template
public:
void f() {
cout << "T == int\n";
}
};
template
public:
void f() {
cout << "U == double\n";
}
};
template
public:
void f() {
cout << "T* used \n";
}
};
template
public:
void f() {
cout << "U* used\n";
}
};
template
public:
void f() {
cout << "T* and U* used\n";
}
};
template
public:
void f() {
cout << "T == U\n";
}
};
int main() {
C
C
C
C
C
C
C
// The following are ambiguous:
// 8: C
// 9: C
// 10: C
// 11: C
// 12: C
} ///:~