作为一个模板,编译器不会执行任何自动类型转换。
编译器无法知道你想要模板参数具有第一个函数参数的类型,或第二个函数参数的类型,或者有时是第一个,有时是第二个。相反,编译器要求你明确地写出你的意思。在这种情况下,你可以通过将所需的类型放在尖括号中告诉编译器要使用哪种类型作为模板参数。
示例一:
#include <iostream>
#include <vector>
template<class T>
T my_max(T a, T b){
return (a >= b? a:b);
}
int main() {
int a = 100;
long b = 200;
// auto max = my_max(a, b); // error: no matching function for call to 'my_max(int&, long int&)'
auto max1 = my_max<int>(a, b);
auto max2 = my_max<long>(a, b);
std::cout << "max1 = " << max1 << ", max2 = " << max2 << std::endl;
}
示例二:
#include <iostream>
#include <cstdlib>
/* Compute the greatest common divisor of two integers, using Euclid's algorithm. */
template<class T>
T gcd(T n, T m){
n = std::abs(n);
while(m != 0){
T tmp{n % m};
n = m;
m = tmp;
}
return n;
}
int main() {
int a = 100;
long b = 200;
int c = 15;
auto val1 = gcd<int>(a, b);
auto val2 = gcd<long>(a, b);
auto val3 = gcd(a, c);
std::cout << "val1 = " << val1 << ", val2 = " << val2 << ", val3 = " << val3 << std::endl; // val1 = 100, val2 = 100, val3 = 5
}
Reference
Exploring C++ 11, 2nd Edition.