【C/C++】【模板與泛型】typename

typename的使用場合

  • 模板定義中,表明其後的模板參數是類型參數

    template<typename T, int a, int b> //typename後跟的是一個類型
    int funcadd(T c){...}
    
    
    template<typename T> //typename可以寫爲class
    class Vector{...}
    
  • 使用類的類型成員,用typename來標識這是一個類型

    // ::作用域運算符 訪問類中的靜態成員的時候 類名::靜態成員名
    int Time::mystatic = 5;
    
    //通知編譯器,一個名字代表的是一個類型。這裏typename不能換成class
    template<typename T>
    //必須使用typename
    //typename的目的是告訴編譯器iter是一個類型
    typename my_vector<T>::iter  my_vector<T>::begin(){...}
    

函數指針做其他函數的參數

#include <iostream>
using namespace std;


int sum(int a, int b)
{
    return a + b;
}

int sub(int a, int b)
{
    return a - b;
}

//函數指針做函數參數

//定義函數指針類型
typedef int(*FunType)(int, int);


void testFunc(int i, int j, FunType func)
{
    //可以通過函數指針調用函數
    int res = func(i, j);
    cout << res << endl;
}

int main()
{
    testFunc(1, 2, sum);
    testFunc(1, 2, sub);
    return 0;
}

函數模板範例


//testfunc(3, 4, mf);
template <typename T, typename F>
void testfunc(const T& i, const T& j, F func)
{
	cout << func(i, j) << endl;
}

  • 使用模板參數爲函數指針的函數模板,可調用對象爲實參
//使用模板參數爲函數指針的函數模板
//可調用對象爲參數
#include <iostream>
#include <string>
using namespace std;


int mf(int tmp1, int tmp2)
{
	return tmp1 + tmp2;
}
//函數指針做函數參數

//定義函數指針類型
typedef int(*FunType)(int, int);

void testFunc(int i, int j, FunType func)
{
	//可以通過函數指針調用函數
	int res = func(i, j);
	cout << res << endl;
}

template <typename T, typename F>
void testfunc(const T& i, const T& j, F func)
{
	cout << func(i, j) << endl;
}


//可調用對象所代表的類
class Tc
{
public:
	Tc()
	{
		cout << "構造函數執行" << endl;
	}
	Tc(const Tc& t)
	{
		cout << "拷貝構造函數執行" << endl;
	}

	int operator()(int v1, int v2) const
	{
		return v1 + v2;
	}
};


int main()
{
	//Tc tc;
	//構造函數  拷貝構造函數
    //會產生臨時對象
	//testfunc(1, 2, tc);

	//少調用依次拷貝構造函數 
	//構造函數
	testfunc(1, 2, Tc());

	return 0;
}

默認模板參數

// 類模板 類模板名後必須用<>來提供額外的信息 <>表示這是一個模板
#include <iostream>
#include <string>
using namespace std;

template<typename T = int, int size = 10>
class Arr
{
private:
	T arr[size];
public:
	void func();
};


int main()
{
	Arr<> a;
	Arr<char> b;
	return 0;
}
//函數模板: 老標準只能爲類模板提供默認模板參數,C++11新標準可以爲函數模板提供默認參數
#include <iostream>
#include <string>
using namespace std;


//可調用對象所代表的類
class Tc
{
public:
	Tc()
	{
		cout << "構造函數執行" << endl;
	}
	Tc(const Tc& t)
	{
		cout << "拷貝構造函數執行" << endl;
	}

	int operator()(int v1, int v2) const
	{
		return v1 + v2;
	}
};

template <typename T, typename F=Tc>
void testfunc(const T& i, const T& j, F func=F())
{
	cout << func(i, j) << endl;
}
int main()
{
    //同時給模板參數和函數參數提供缺省值
    //注意寫法 F func = F()
    //Tc重載()
	testfunc(1, 3);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章