C++中的模板template <typename T>

  这个是C++中的模板..template<typename T> 这个是定义模板的固定格式,规定了的..模板应该可以理解到它的意思吧.. 比如你想求2个int float 或double型变量的值,只需要定义这么一个函数就可以了,假如不用模板的话,你就必须针对每种类型都定义一个sum函数..int sum(int, int);float sum(float, float);double sum(double, double);

1.因为T是一个模版实例化时才知道的类型,所以编译器更对T不知所云,为了通知编译器T是一个合法的类型,使用typename语句可以避免编译器报错。 
2.template < typename var_name > class class_name; 表示var_name是一个类型, 在模版实例化时可以替换任意类型,不仅包括内置类型(int等),也包括自定义类型class。 换句话说,在template<typename Y>和template<class Y>中, 
typename和class的意义完全一样。 
建议在这种语句中尽可能采用typename,以避免错觉(因为只能替换class,不能只换int), 
这也是C++新标准引进typename关键词的一个初衷

   下面我们以求两个数中的最大值为例介绍Template(模板)的使用方法。

  1.  
    <pre name= "code" class="cpp">// TemplateTest.cpp : 定义控制台应用程序的入口点。
  2.  
    ///<summary>
  3.  
    ///测试C++中的template(模板)的使用方法 最新整理时间2016.5.21
  4.  
    ///</summary>
  5.  
    ///<remarks>1:template的使用是为了简化不同类型的函数和类的重复定义.
  6.  
    ///<remarks>2:char类型变量c,d输入的都是字母,不是数字,如输入32则c=3,d=2.
  7.  
    #include "stdafx.h"
  8.  
    #include <iostream>
  9.  
    #include< vector>
  10.  
    using namespace std;
  11.  
    template <typename T>
  12.  
    T mmax(T a,T b)
  13.  
    {
  14.  
    return a>b?a:b;
  15.  
    }
  16.  
    int _tmain(int argc, _TCHAR* argv[])
  17.  
    {
  18.  
    cout<<"Please enter the value of a and b:"<<endl;
  19.  
    int a,b;
  20.  
    cin>>a>>b;
  21.  
    cout<<mmax(a,b)<<endl;
  22.  
    cout<<"Please enter the value of c and d:"<<endl;
  23.  
    char c,d;
  24.  
    cin>>c>>d;
  25.  
    cout<<mmax(c,d)<<endl;
  26.  
    cout<<"Please enter the value of f and g:"<<endl;
  27.  
    double f,g;
  28.  
    cin>>f>>g;
  29.  
    cout<<mmax(f,g)<<endl;
  30.  
    while(1);
  31.  
    return 0;
  32.  
    }
    转载:https://blog.csdn.net/fightingforcv/article/details/51472586

猜你喜欢

转载自www.cnblogs.com/wx-zhizhe/p/9381054.html