標籤:
#include <iostream>
#include <typeinfo>
using namespace std;
template <class T>
T add(T one, T two)
{
cout << "類型:" << typeid(T).name() << endl;
return one + two; // 函數模板只有在調用時才編譯,有的編譯器在初次編譯時間就會編譯
}
int add(int one, int two)
{
cout << "自訂int" << endl;
return one + two;
}
template <class T, class F> //函數模板不僅可以接受資料類型,還可以接受操作類型
void show(T t, F f)
{
f(t);
}
void show_(int temp)
{
cout << temp << endl;
}
template<class T1, class T2>
auto temp1(T1 t1, T2 t2)->decltype(t1+t2) //自動型別推斷
{
return t1 + t2;
}
template<class T>
void temp2(T t)
{
decltype(t) d; //建立一個與T類型相同的變數
}
int main()
{
//cout << add(1.2, 1.2) << endl;
//cout << add(1, 2) << endl; //如果有自訂函數 int add(int, int),則會優先使用自訂的,不然會使用函數模板
//cout << add<int>(1,2) << endl; //如果函數模板執行個體化,則無論有沒有自訂函數add,都會使用函數模板
//show(1, show_);
//show(1, [](int i){cout << i << " lambda" << endl;}); //可以把lambda運算式作為操作類型傳給函數模板
//int a = 10;
//decltype(a) b = 3; //decltype的功能是拷貝資料類型
//cout << temp(1.2, 1) << endl;
//cout << temp(1, 1.2) << endl;
return 0;
}
C++函數模板複習