c++函数模板
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
template<typename T>
int compare(const T &v1, const T &v2)
{
if (v1 < v2)
{
return -1;
}
if (v1 > v2)
{
return 1;
}
return 0;
}
template<class T>
T absValue(T val)
{
return val > 0 ? val : -val;
}
template<typename T1,typename T2>
T1& print_define(T1& t1, T2 val)
{
t1 << val;
return t1;
}
template<typename T>
const T& bigger(const T& v1, const T& v2)
{
return v1 > v2 ? v1:v2;
}
int main()
{
//int x1 = 4;
//int x2 = 3;
double x1 = 4.5;
double x2 = 4.5;
int rx = compare(x1, x2);
cout << rx << endl;
double val1 = -0.76;
cout << absValue(val1)<< endl;
double dval = -0.98;
float fval = -12.3;
string oristr = "this is a test";
string desstr;
ostringstream oss(desstr);
ofstream outfile("result.txt");
print_define(cout, -3) << endl;
print_define(cout, dval) << endl;
print_define(cout, fval) << endl;
print_define(cout, oristr) << endl;
print_define(outfile, -3) << endl;
print_define(outfile, dval) << endl;
print_define(outfile, fval) << endl;
print_define(outfile, oristr) << endl;
outfile.flush();
outfile.close();
cout << bigger(val1,dval)<< endl;
system("pause");
return 0;
}
-------------------------------------------------------------------------------
0
0.76
-3
-0.98
-12.3
this is a test