//C++模板類複習
#include<iostream>
using namespace std;
template <class T1, class T2 = string>
class test
{
private:
T1 temp1;
T2 temp2;
public:
test(){}
test(T1 data1, T2 data2):temp1(data1),temp2(data2){}
void show();
};
template <class T1, class T2> //定義模板類成員
void test<T1, T2>::show()
{
cout << "原始類" << endl;
cout << temp1 << endl << temp2 << endl;
}
template <> //顯示具體化
class test<int, int>
{
private:
int temp1;
int temp2;
public:
test(){}
test(int one, int two):temp1(one), temp2(two){}
void show()
{
cout << "具體化" << endl;
cout << temp1 << endl << temp2 << endl;
}
};
template <class T>
class test<T, double>
{
private:
T temp1;
double temp2;
public:
test(){}
test(T data1, double data2):temp1(data1), temp2(data2){}
void show()
{
cout << "部分具體化" << endl;
cout << temp1 << endl << temp2 << endl;
}
};
template class test<double, double>; //模板類的顯示具體化和顯示實例化不會衝突,因爲顯示具體化不會創建類聲明
//將模板類作爲內置成員
template <class T1>
class test1
{
private:
template <class T2>
class test2
{
private:
T2 data2;
public:
test2(){}
test2(T2 d):data2(d){}
void show2()
{
cout << data2 << endl;
}
};
test2<T1> data1;
public:
test1(T1 d):data1(d){}
void show1()
{
data1.show2();
}
};
template <template <class T1, class T2> class te>
class test3
{
private:
te<int, int> a;
public:
test3(te<int, int> d):a(d){}
void show1()
{
a.show();
}
};
int main()
{
//test<int> a(1, "linukey");//第二個參數將用默認參數string
//a.show();
//test<double, double> a(5, 6);//隱式實例化
//a.show();
//test<int,int> a(5, 6);//因爲有了int,int 的顯示具體化,所以此次使用具體化類
//a.show();
//test<int, double> a(1, 2.1);//部分具體化
//a.show();
//test1<int> a(1); //模板類作爲類內置成員
//a.show1();
//test<int, int> a(1, 2); //模板類作爲參數
//test3<test> b(a);
//b.show1();
return 0;
}
C++模板類複習
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
C++智能指針模板類複習
//C++智能指針模板類複習 #include<iostream> #include<memory> using namespace std; //
linukey
2020-06-23 06:00:02
模板元編程加速遞歸
//模板元編程加速遞歸 //缺點:模板元在編譯時處理,無法調試,並且會加大代碼體積 #include<iostream> using namespa
linukey
2020-06-23 06:00:02
C++類轉換構造函數和轉換函數複習
//C++類轉換構造函數和轉換函數複習 #include<iostream> #include<string> using namespace st
linukey
2020-06-23 06:00:02
C++ lambda表達式複習
linukey
2020-02-23 19:47:32
C++中類const、static、static const成員變量
linukey
2020-02-23 19:47:32
C++實現C語言printf函數
linukey
2020-02-23 19:47:32
C++ 在堆上開闢與釋放二維、三維指針
linukey
2020-02-23 19:47:32
利用包裝器以及lambda表達式實現二叉查找樹
linukey
2020-02-23 19:47:32
extern
yuwei19840916
2020-02-23 15:07:22
linux下查看so文件的函數列表
赵小刚
2020-02-22 22:52:11
24小時熱門文章
-
再談23種設計模式(3):行爲型模式(學習筆記)
-
Power Automate Desktop 安裝完,登錄後老是提示one driver 錯誤
-
微前端學習筆記(4):從微前端到微模塊之EMP與hel-micro方案探索
-
微前端學習筆記(1):微前端總體架構概述,從微服務發微
-
985 碩士程序員,空窗 4 個月沒有 Offer!
-
一文搞懂 Spring 循環依賴
-
賽博鬥地主——使用大語言模型扮演Agent智能體玩牌類遊戲。
-
VScode右鍵打開(添加到右鍵)
-
記一次 .NET某工控視覺自動化系統 卡死分析
-
WindowsServer--SQL Server搭建主從同步實現讀寫分離 - 事務性分發