C++模板和STL
例:
#include <iostream>
using namespace std;
template <typename T>
T max(T x, T y){
return x<y?y:x;
}
int main(void){
int i1=100,i2=200;
cout<<::max<int>(i1,i2)<<endl;
double d1=1.23,d2=4.56;
cout<<::max<double>(d1,d2)<<endl;
string s1="world",s2 = "hello";
cout<<::max<string>(s1,s2)<<endl;
char str1[] = "world";
char str2[] = "hello";
cout<<::max<string>(str1,str2)<<endl;
return 0;
}
参考代码:
#include <iostream>
using namespace std;
template <typename T>
T add(T x,T y){
return x+y;
}
class Complex{
public:
Complex(int r,int i):m_r(r),m_i(i){}
friend ostream& operator<<(ostream& os,const Complex& c){
os<<c.m_r<<"+" <<c.m_i<<"i";
return os;
}
const Complex operator+(const Complex& c)const{
Complex res(m_r+c.m_r,m_i+c.m_i);
return res;
}
private:
int m_r;
int m_i;
};
int main(void){
cout<<add<int>(123,456)<<endl;
cout<<add<double>(1.23,4.56)<<endl;
Complex c1(1,2);
Complex c2(3,4);
cout<<c1<<","<<c2<<endl;
cout<<add<Complex>(c1,c2)<<endl;
}
|