【轉載】C++中的模板template <typename T>
阿新 • • 發佈:2018-02-12
最新 bsp 針對 www. code mark 方法 固定格式 應該
從一位大佬的程序中看到的,好像挺牛的!!
這個是C++中的模板..template<typename T> 這個是定義模板的固定格式,規定了的..模板應該可以理解到它的意思吧.. 比如你想求2個intfloat 或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(模板)的使用方法。
<pre name="code" class="cpp">// TemplateTest.cpp : 定義控制臺應用程序的入口點。 ///<summary> ///測試C++中的template(模板)的使用方法 最新整理時間2016.5.21 ///</summary> ///<remarks>1:template的使用是為了簡化不同類型的函數和類的重復定義. ///<remarks>2:char類型變量c,d輸入的都是字母,不是數字,如輸入32則c=3,d=2. #include "stdafx.h" #include <iostream> #include<vector> using namespace std; template <typename T> T mmax(T a,T b) { return a>b?a:b; } int _tmain(int argc, _TCHAR* argv[]) { cout<<"Please enter the value of a and b:"<<endl; int a,b; cin>>a>>b; cout<<mmax(a,b)<<endl; cout<<"Please enter the value of c and d:"<<endl; char c,d; cin>>c>>d; cout<<mmax(c,d)<<endl; cout<<"Please enter the value of f and g:"<<endl; double f,g; cin>>f>>g; cout<<mmax(f,g)<<endl; while(1); return 0; }
【轉載】C++中的模板template <typename T>