觀察以下函數模板實例,雖然解決了不同類型比較的問題,但又產生了新的問題。
#include
using namespace std;
template
T1 const &max(T1 const &a,T2 const & b)
{
return a>b?a:b;
}
void main()
{
cout<<"max(10,9.4)="<<max(10,9.4)<<endl;
cout<<"max(5.6,7.8)="<<max(5.6,7.8)<<endl;
cout<<"max(9.5,6)="<<max(9.5,6)<<endl;
cout<<"max(9,11.2)="<<max(9,11.2)<<endl;
}
以上實例返回值最後一個存在問題,有以下解決方案:
1.顯示實例化該參數模版;
#include
using namespace std;
template
T1 max(T1 const &a,T2 const & b)
{
return a>b?a:b;
}
void main()
{
cout<<"max(10,9.4)="<<MAX(10,9.4)<<ENDL;< p>
cout<<"max(5.6,7.8)="<<MAX(5.6,7.8)<<ENDL;< p>
cout<<"max(9.5,6)="<<MAX(9.5,6)<<ENDL;< p>
cout<<"max(9,11.2)="<<MAX(9,11.2)<<ENDL;< p>
}
2. 引入新的模版類型,來定義函數模板的返回類型。
#include
using namespace std;
template
T3 max(T1 const &a,T2 const & b)
{
return a>b?a:b;
}
void main()
{
cout<<"max(10,9.4)="<<MAX(10,9.4)<<ENDL;< p>
cout<<"max(5.6,7.8)="<<MAX(5.6,7.8)<<ENDL;< p>
cout<<"max(9.5,6)="<<MAX(9.5,6)<<ENDL;< p>
cout<<"max(9,11.2)="<<MAX(9,11.2)<<ENDL;< p>
}