1、在编写模板函数时,通常在形参中会使用到泛型类型,这样在调用泛型函数时,直接使用就可一了,如果泛型函数没有参数,而函数内部使用了泛型类型,如果直接调用就会出错,而应个在函数名后明确指明泛型的类型。我觉得,对于第一种情况,由于编译器可以从参数中获得泛型的类型,所以不用明确指定了,而对于第二种情况,因为编译器无法从参数中获得泛型的类型,所以必须明确指定。举例如下:
#include <stdio.h>
template<typename T>
T Test() {
T aa;
return aa;
}
template<typename T>
T Test3(int) {
}
template<typename T>
T Test1(const T& left, const T& right) {
return left + right;
}
int main(int argc, char** argv) {
Test(); //error
Test<int>(); //correct
Test1(2, 3); //correct
Test1<int>(2, 3); //correct
Test3(1); //error
Test3<int>(1); //correct
}


被折叠的 条评论
为什么被折叠?



