模板声明顺序在 C++ 中重要吗

Does template declaration order matter in c++

以下代码摘自http://www.gotw.ca/publications/mill17.htm

#include<iostream>
using namespace std; 

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

template<class T> // (b) a second base template, overloads (a) 
void f( T* ){
  cout << "base2\n";   
}

template<>        // (c) explicit specialization of (b) 
void f(int*){
  cout << "base3\n";   
}

int main()
{
  int *p = NULL; 
  f( p ); 
}

上述情况的输出是"base3"。但是如果我在 (b) 上面写 (c),输出是 "base2"。我在 cpp.sh 测试了上面的代码。谁能告诉我原因吗?

是的,这里的顺序很重要。如果将 (c) 移到 (b) 之前,那么它就变成了 (a) 而不是 (b) 的显式特化。

在两个主要模板(即(a)和(b))之间的重载决议中,始终选择(b);但是 (c) 不是 (b) 的特化,因此不会被调用,所以你会得到输出 "base2".