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 };
};
这是编译期便能够算出结果的。
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章