[英]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上測試了上面的代碼。 誰能告訴我原因?
是的,訂單在這里很重要。 如果你在(b)之前移動(c),那么它變成(a)而不是(b)的顯式特化。
在兩個主要模板之間的重載分辨率中,即(a)和(b),總是選擇(b); 但是(c)不再是(b)的特化,然后不會被調用,所以你得到輸出“base2”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.