#include <iostream>
#include <stdlib.h>
template<typename T>
T max(T a, T b) {
return (((a) > (b)) ? (a) : (b));
}
int main()
{
// This will call max<int> by implicit argument deduction.
std::cout << max(3, 7) << std::endl;
// This will call max<double> by implicit argument deduction.
std::cout << max(3.0, 7.0) << std::endl;
// This depends on the compiler. Some compilers handle this by defining a template
// function like double max <double> ( double a, double b);, while in some compilers
// we need to explicitly cast it, like std::cout << max<double>(3,7.0);
//std::cout << max(3, 7.0) << std::endl;
std::cout << max<double>(3, 7.1) << std::endl;
return 0;
}
当两个参数类型不一致在vs中
max<double>(3,7.1)
output:7.1
#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename T1,typename T2 ,int NUM> double fun(T1 a,int b,T2 c)
{
int number = 0;
return a*(number + b)*c; // number 可以当做int类型变量使用
}
int main() {
cout << fun<double,int,5>(3.0, 5, 6);
return 0;
}