lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

[cpp]:  以模板作为模板参数 -- <template>

 

 

 

 

一、template 说明

 

  1、模板参数:以‘模板’作为模板的参数。

 

  2、示例

1 //   template<class T1, class T2> class W:模板参数W
2 //   W<T1, T2>: W有两个参数【T1, T2】
3 
4 template<class U, class V, template<class T1, class T2> class W>
5 class object{};

 

 

 

二、代码

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 
 5 using namespace std;
 6 
 7 //  分割线
 8 void sep(){ cout << "" << endl; }
 9 
10 //  模板有2个类型参数【U,V】
11 template<class U, class V>
12 class B{
13 public:
14     B(){}
15     void msgb(){ cout << "[os]: B::msgb() " << endl;  }
16 };
17 
18 //  模板有1个类型参数【T】
19 template<typename T>
20 class A
21 {
22 public:
23     A(){}
24     void msga1() { cout << "[os]: A::msga1() " << endl; }
25     void printa1(){ cout << "[os]: A::printa1() " << endl; }
26 public:
27     T i;
28 };
29 
30 //  模板有1个类型参数【T】
31 template<typename T>
32 class A<T*>
33 {
34 public:
35     A(){}
36     void msga2() { cout << "[os]: A::msga2() " << endl; }
37     void printa2(){ cout << "[os]: A::printa2() " << endl; }
38 public:
39     T *f;
40 };
41 
42 //  模板共有3个参数:    模板有2个类型参数【U,V】, 一个模板参数【W】(W有1个参数【T1】)
43 //  模板参数 以模板作为模板的参数:
44 //  模板参数【W】有1个参数; C实例化的时候,第三个模板参数必须是带有1个模板参数的类('类A'符合条件,'类A'带有1个参数【T】)
45 template<class U, class V, template<typename T1> class W>
46 class C
47 {
48 public:
49     C(){}
50     void msgc() { cout << "[os]: C::msgc() " << endl; }
51     void printcy(){ cout << "[os]: C::printcy()  " << endl; }
52     void printcz(){ cout << "[os]: C::printcz()  " << endl; }
53     W<U> y;
54     W<V*> z;
55 };
56 
57 //  模板共有3个参数:    模板有2个类型参数【U,V】, 一个模板参数【W】(W有1个参数【T1】)
58 //  模板参数 以模板作为模板的参数:
59 //  模板参数【W】有2个参数; D实例化的时候,第三个模板参数必须是带有2个模板参数的类('类B'符合条件,'类B'带有2个参数【T,V】)
60 template<class U, class V, template<typename T1, typename T2> class W>
61 class D{
62 public:
63     D(){}
64     void msgd(){ cout << "[os]: D::msg() " << endl;  }
65 };
66 
67 //
68 void run ()
69 {
70     A<int> a1;
71     a1.printa1();
72   
73     sep();
74 
75     A<float*> a2;
76     a2.printa2();
77 
78     sep();
79 
80     C<int, float, A> c;        //  C实例化时,A位置必须是'带有1个模板参数'的类名; A是类名 。
81     c.printcy();
82 
83     sep();
84     
85     D<int, float, B> d;        //  D实例化时,B位置必须是'带有2个模板参数'的类名; B是类名 。
86     d.msgd();  
87 }
88 
89 //  程序入口/主函数
90 int main()
91 {
92     run();
93     return 0;
94 }

 

 

 

三、运行结果

 1 g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
 2 
 3 
 4 [os]: A::printa1() 
 5 
 6 [os]: A::printa2() 
 7 
 8 [os]: C::printcy()  
 9 
10 [os]: D::msg()

 

 

 

四、参考文献

 

  1、  Template parameters and template arguments  --  https://en.cppreference.com/w/cpp/language/template_parameters#Type_template_parameter

 

  2、  cpp 在线编译工具  --  https://coliru.stacked-crooked.com/

 

 

posted on 2024-01-13 00:21  lnlidawei  阅读(4)  评论(0编辑  收藏  举报