我正在学习 C++ 中的模板,我发现了以下示例。
据我所知,如果没有匹配的非模板函数,编译器应该总是尝试使用最“专业”的模板,但在这个例子中,第一次调用导致调用函数 a(T*) 而不是一个(整数*)。为什么?为什么第二次调用的行为不同?
template<typename T> void a(T) {cout << "(T)" << endl;} template<> void a<>(int*) {cout << "(int)" << endl;} template<typename T> void a(T*) {cout << "(T*)" << endl;} template<typename T> void b(T) {cout << "(T)" << endl;} template<typename T> void b(T*) {cout << "(T*)" << endl;} template<> void b<>(int*) {cout << "(int)" << endl;} int main() { int i; a(&i); b(&i); return 0; }
The resulting output is:
(T*)
(int)
我希望它是:
(int)
(int)
最佳答案
仅考虑主模板(因此没有特化)来选择更特化的重载。
一旦使用主模板完成选择,我们将使用特化(如果有的话)。
现在,template<> void a<>(int*);
只能是template<typename T> void a(T)
的特化(其他版本没看过)。
和template<> void b<>(int*);
是template<typename T> void b(T*)
的特化(它是更专业的匹配重载)。
请注意,您可以选择 b
的特化通过提供模板而不是让编译器推断:
-
template<> void b<>(int*)
->template<typename T> void b(T*) with T=int
-
template<> void b<int>(int*)
->template<typename T> void b(T*) with T=int
-
template<> void b<int*>(int*)
->template<typename T> void b(T) with T=int*
因此:
int i;
a(&i); // a<T*> with T=int*, no specialization for a<U*> (U=int) exist -> generic template called
b(&i); // b<T*> with T=int*, specialization for b<U*> (U=int) exists -> specialization called
关于c++ - 如何确定将使用哪个模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56473597/