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

发布时间 2024-01-13 00:26:22作者: 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个类型参数
11 template<class U, class V>
12 class B{
13 public:
14     B(){}
15     void msgb(){ cout <<"[os]: B::msg() " << endl;  }
16 };
17 
18 //  模板有1个类型参数
19 template<typename T>
20 class A
21 {
22 public:
23     A(){}
24     void msg1() { cout <<"[os1]: object " << endl; }
25     void print1(){ cout <<"[os1]: i " << endl; }
26 public:
27     T i;
28 };
29 
30 //  模板有1个类型参数
31 template<typename T>
32 class A<T*>
33 {
34 public:
35     A(){}
36     void msg2() { cout <<"[os2]: object<T*> " << endl; }
37     void print2(){ cout <<"[os2]: f " << endl; }
38 public:
39     T *f;
40 };
41 
42 //  模板有2个类型参数【U V】,一个模板参数带(有1个参数【T1】)
43 //  模板参数 以模板作为模板的参数:
44 template<class U, class V, template<typename T1> class W>
45 class C
46 {
47 public:
48     C(){}
49     void msg3() { cout <<"[os3]: C<V> " << endl; }
50     void print3y(){ cout <<"[os3]: y.i  "<< endl; }
51     void print3z(){ cout <<"[os3]: z.i  "<< endl; }
52     W<U> y;
53     W<V*> z;
54 };
55 
56 //  模板有2个类型参数【U V】,一个模板参数带(有2个参数【T1 T2】)
57 //  模板参数 以模板作为模板的参数:
58 template<class U, class V, template<typename T1, typename T2> class W>
59 class D{
60 public:
61     D(){}
62     void msgd(){ cout <<"[os]: D::msg() " << endl;  }
63 };
64 
65 //
66 void run ()
67 {
68     A<int> a1;
69     a1.print1();
70   
71     sep();
72 
73     A<float*> a2;
74     a2.print2();
75 
76     sep();
77 
78     C<int,float,A> c;
79     c.print3y();
80     c.print3z();
81 
82     sep();
83     D<int,float,B> d;
84     d.msgd();  
85 }
86 
87 //
88 int main()
89 {
90     run();
91     return 0;
92 }

 

 

 

三、运行结果

 1 g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
 2 
 3 
 4 [os1]: i 
 5 
 6 [os2]: f 
 7 
 8 [os3]: y.i  
 9 [os3]: z.i  
10 
11 [os]: D::msg()

 

 

 

四、参考文献

 

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