#include <iostream>
template <class T>
void foo(T) {
std::cout << "foo(T)" << std::endl;
}
template <class T>
void foo(T*) { //#3
std::cout << "foo(T*)" << std::endl;
}
#define TEST
#ifdef TEST
template <>
void foo(int*) { //#1
std::cout << "foo(int*)" << std::endl;
}
#else
template <>
void foo<int*>(int*) { //#2
std::cout << "foo<int*>(int*)" << std::endl;
}
#endif
int main(int argc, char **argv) {
int* p = 0;
foo(p);
return 0;
}
#1和#2有什麼區別。如果我定義TEST,#1工作。但是,如果我評論它,#3 工作...哪個是寫功能模板專業化的正確方法...函數模板專精失敗?
有一些情境它是方便或需要指定模板參數(S) 。需要指定參數的顯而易見的地方在於如果模板參數未被推導出來。方便的地方在於何時需要將參數引導至適當轉換的類型。當你想明確指定參數時,你經常不能使用重載。 –