Skip to main content


Showing posts from January, 2008

Function Template Overload Resolution and Specialization Anomaly

I recently realized that function template overloading and function template specialization can interact with each other in complex ways giving rise to quite surprising C++ programs. Consider,

template<class T> // (a) a base template
void f( T ) {
std::cout << "f(T)\n";

void f<>(int*) { // (b) an explicit specialization
std::cout << "f(int *) specilization\n";

template<class T> // (c) another, overloads (a)
void f( T* ) {
std::cout << "f(T *)\n";

int main (void) {
int *p = 0;

Output of the above program is "f(T *)" (i.e. (c) is invoked in main). Now simply swap the order in which (b) and (c) are written. The output of the program changes! This time it invokes (b) giving output as "f(int *) specilization".

The reason behind it is that when the integer full specilization (b) of f is defined in the order shown above, it is a full specialization of (a). But (c) is a better matc…