类模板的具体化

 1 #include <iostream>
 2 
 3 //类模板的具体话
 4 //1.首先 类模板的完全模板化一定要声明在最前面
 5 //2.类模板的优先级 完全具体化>半具体化>完全模板化
 6 
 7 //定义一个完全模板化的类
 8 template <class T1,class T2>
 9 class A
10 {
11 public:
12     T1 m_i;
13     T2 m_s;
14     A(T1 i, T2 s) :m_i(i), m_s(s)
15     {
16         std::cout << "完全模板化类的构造函数" << std::endl;
17     }
18 };
19 
20 //定义一个半模板化的类
21 template <class T2>
22 class A<int,T2>
23 {
24 public:
25     int m_i;
26     T2 m_s;
27     A(int i, T2 s) :m_i(i), m_s(s)
28     {
29         std::cout << "半模板化类的构造函数" << std::endl;
30     }
31 };
32 //定义一个具体化的类
33 template <>
34 class A<int,std::string>
35 {
36 public:
37     int m_i;
38     std::string m_s;
39     A(int i, std::string s) :m_i(i), m_s(s)
40     {
41         std::cout << "完全具体化类的构造函数" << std::endl;
42     }
43 };
44 
45 int main()
46 {
47     A<int, std::string>(10, "完全具体化");  //注意 这里<int,std::string> 类型定义不能省掉 如果不显示定义 让编绎器自行推导 将会调用完全模板化类
48     A<int,int>(10, 20);//半俱体化
49     A<char,char>('b', 'c');//完全俱体化
50 
51     return 0;
52 }

 

posted on 2026-01-27 10:42  海的寂寞  阅读(0)  评论(0)    收藏  举报

导航