[cpp]: 获取“实例对象”--template 编程
一、代码
1 #include <iostream>
2 #include <string>
3
4
5 using namespace std;
6
7
8 class base { };
9
10
11 class work:base {
12 public:
13 work(){}
14 work(string s1, string s2){}
15 work(string nc, string s1, string s2){ }
16 string get_type(){ return type; }
17 private:
18 string type = "work";
19 };
20
21
22 class book:base{
23 public:
24 book(){}
25 string get_type(){ return type; }
26 private:
27 string type = "book";
28 };
29
30
31
32
33 /**** important: begin *****/
34
35
36 // return object of type 'work'
37 work
38 set_class(string s1, string s2)
39 {
40 return work(s1,s2);
41 }
42
43
44 // return object of type 'T'; general program;
45 template<class T, class ...U>
46 T
47 get_object(U ...u)
48 {
49 return T();
50 }
51
52
53 /**** important: end *****/
54
55
56
57
58 // systhesis
59 void run()
60 {
61 string s1="hello"; string s2="world";
62
63 cout << s1 << ", " << s2 << endl;
64
65 cout << "object0_type := " << set_class(s1,s2).get_type() << endl;
66
67 cout << "object1_type := " << get_object<work, string>(s1).get_type() << endl;
68
69 cout << "object2_type := " << get_object<work, string>(s1,s2).get_type() << endl;
70
71 cout << "object3_type := " << get_object<book>(1).get_type() << endl;
72
73 cout << "object4_type := " << get_object<book>(1, 'c').get_type() << endl;
74
75 cout << "object5_type := " << get_object<book>(1, 'c', "string").get_type() << endl;
76
77 cout << "object6_type := " << get_object<book>(1, 'c', 3.14, "string").get_type() << endl;
78 }
79
80
81 // test part; entrance
82 int main()
83 {
84 run();
85
86 return 0;
87 }
二、运行结果
1 g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
2
3 hello, world
4 object0_type := work
5 object1_type := work
6 object2_type := work
7 object3_type := book
8 object4_type := book
9 object5_type := book
10 object6_type := book
三、参考资料:
1、parameter pack -- https://en.cppreference.com/w/cpp/language/parameter_pack
2、Template parameters and template arguments -- https://en.cppreference.com/w/cpp/language/template_parameters#Type_template_parameter
本文由 lnlidawei 原创、整理、转载,本文来自于【博客园】; 整理和转载的文章版权归属【原创作者】; 转载或引用时【请保留文章的来源信息】:https://www.cnblogs.com/lnlidawei/p/17955662

浙公网安备 33010602011771号