The following code is taken from 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 );
}
The output in the above case is "base3". But if I write (c) above (b), the output is "base2". I tested the above code at cpp.sh. Can anyone please tell me the reason?
Yes, the order matters here. If you move (c) before (b), then it becomes an explicit specialization of (a) instead of (b).
In overload resolution between the two primary templates, ie (a) and (b), (b) is always selected; but (c) is not the specialization of (b) again and then won't be invoked, so you'll get the output "base2".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.