在前面的示例中,我們使用的函數模板的實參都是一樣的,但其實函數模板的參數也可以不一樣,並且可以是多個
,這樣就可以定製化一些特殊用途的函數模板,例如:
//函數模板的參數
#include <iostream>
#include <string>
template <typename T1, typename T2>
inline T1 max2(T1 const& a, T2 const& b) //這是返回參數一定要用T1,不能是T1 const&
{
return a < b ? b : a; //返回局部變量或臨時變量的地址
}
template <typename RT, typename T1, typename T2>
inline RT max3(T1 const& a, T2 const& b)
{
return a < b ? b : a;
}
int main()
{
int i = 42;
std::cout << "max2(8.2, i)=======" << ::max2(8.2, 'A') << std::endl;
double d1 = 3.9;
double d2 = 8.9;
std::cout << "max2(d1, d2)=====" << ::max2(d1, d2) << std::endl;
float f1 = 4.5f;
float f2 = 7.4f;
std::cout << "max2(f1, f2)=====" << ::max2(f1, f2) << std::endl;
std::string s1 = "camleA";
std::string s2 = "scott";
std::cout << "max2(s1, s2)=====" << ::max2(s1, s2) << std::endl;
//模板實參演繹並不適合返回類型,因爲RT不會出現在函數調用參數的類型裏面。
//因此,函數調用並不能演繹出RT,必須顯示地指定模板實參列表,
//std::cout << "max3(d1, d2)=====" << ::max3(d1, d2) << std::endl;//error:未找到匹配的重載函數,未能爲“RT”推導模板參數
std::cout << "max3(d1, d2)=====" << ::max3<double, int, double>(i, d2) << std::endl;
std::cout << "max3(d1, d2)=====" << ::max3<double>(d1, d2) << std::endl;//指定模板第一個參數RT爲double類型
}
函數模板參數傳遞在編譯的時候就已經確定了,所以max3參數傳遞的過程中嚴格按順利傳參
max3<double, int, double>(i, d2)
RT指定的是double型, T1指定的是int型, T2指定的是double型,順序不能亂。
max3<double>(d1, d2)
這種表示RT指定的是double型,即返回類型,T1和T2由傳入的d1,d2指定。