C++ template Day Day Up 第三天 模板函數的重載
從C++ templates粘一段例子下來:
// maximum of two int values
inline int const& max (int const& a, int const& b)
{
return a<b?b:a;
}
// maximum of two values of any type
template <typename T>
inline T const& max (T const& a, T const& b)
{
return a<b?b:a;
}
// maximum of three values of any type
template <typename T>
inline T const& max (T const& a, T const& b, T const& c)
{
return max (max(a,b), c);
}
int main()
{
::max(7, 42, 68); // calls the template for three arguments
::max(7.0, 42.0); // calls max<double> (by argument deduction)
::max('a', 'b'); // calls max<char> (by argument deduction)
::max(7, 42); // calls the nontemplate for two ints
::max<>(7, 42); // calls max<int> (by argument deduction)
::max<double>(7, 42); // calls max<double> (no argument deduction)
::max('a', 42.7); // calls the nontemplate for two ints
}
恩,這個例子淺顯易懂,可以根據它看出來編譯器的推斷規則。
重要的是看下面這個例子:
template<typename T>
void fun(T* t)
{
cout<<"fun with pointer/n";
}
template<typename T>
void fun(T t)
{
cout<<"fun normal/n";
}
// main
int i = 5;
fun(&i); //[a]
fun(i); //[b]
[a]和[b]分別輸出:
fun with pointer
fun normal
這說明可以根據模板參數來區分參數的類型,這也依賴於deduction。
例如可以通過下面的代碼來檢驗一個類型是否爲指針。
template<typename T>
struct IsPointer
{
enum{ Result = false };
};
template <typename T>
struct IsPointer<T*>
{
enum{ Result = true };
};
這是編譯期便能夠算出結果的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.