深入理解:編譯器從函式模板通過具體型別產生不同的函式。
編譯器會對函式模板進行兩次編譯:對模板**本身進行編譯,對引數替換後的**進行編譯。
注意事項:函式模板本身不是函式,是產生函式模子,因此模板本身不允許隱式型別轉換,自動推導型別時,必須嚴格匹配。顯示型別指定時,能夠進行隱式型別轉換。
#include
#include
using namespace std;
class test
};template < typename t >
void swap(t& a, t& b)
typedef void(funci)(int&, int&); //函式型別 返回值void,型別名字funcl,引數int&, int&
typedef void(funcd)(double&, double&);
typedef void(funct)(test&, test&);
int main()
函式模板可以定義任意多個不同的型別引數
template
t1 add(t2 a, t3 b)
return static_cast(a+b);
用法==>int r=add(0.5,0.8);
對於多引數函式模板:無法自動推導返回值型別,可以從左向右部分指定型別引數。
//t1=int,t2=double,t3=double
int r1=add(0.5,0.8)
//t1=int,t2=float,t3=double
int r2=add(0.5,0.8);
//t1=int,t2=float,t3=float
int r3=add(0.5,0.8);
工程中將返回值型別作為第乙個引數型別。
#include
#include
using namespace std;
template
< typename t1, typename t2, typename t3 >
t1 add(t2 a, t3 b)
int main()
當函式過載遇上函式模板會發生什麼? 能夠同時出現
函式模板可以像普通函式一樣被過載,c++編譯器優先考慮普通函式,如果函式模板可以產生乙個更好的匹配,那麼選擇模板,可以通過空模板實參列表限定編譯器只匹配模板。
int r1=max(1,2);
double r2=max<>(0.5,0.8); //---->限定編譯器只匹配函式模板
#include
#include
using namespace std;
template < typename t >
t max(t a, t b)
int max(int a, int b) //過載
template < typename t >
t max(t a, t b, t c)
int main()
函式模板通過具體型別產生不同的函式,函式模板可以定義任意多個不同的型別引數,函式模板返回值型別必須顯示指定,函式模板可以像普通函式一樣被過載。
57 深入理解函式模板
1 函式模板深入理解 編譯器從函式模板通過具體型別產生不同的函式 編譯器會對函式模板進行兩次編譯 1 對模板 本身進行編譯 2 對引數替換後的 進行編譯 程式1 證明編譯器會對函式模板進行兩次編譯 include include using namespace std class test temp...
C 57 深入理解函式模板
include using namespace std class test template typename t void swap t a,t b typedef void funci int int typedef void funcd double double typedef void ...
第57課 深入理解函式模板
本文內容來自於對狄泰學院 唐佐林老師 c 深度解析 課程的學習總結 函式模板 編譯器從函式模板通過具體型別 產生不同的函式 編譯器會 對函式模板進行兩次編譯 注意事項 函式模板本身不允許隱式型別轉換 實驗 include include using namespace std class test ...