cpp: 获取“实例对象”-- template 编程

发布时间 2024-01-10 04:27:39作者: lnlidawei

cpp:   获取“实例对象”-- template 编程

 

 

 

一、代码

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 class base { };
 7 
 8 class work:base {
 9 public:
10     work(){}
11     work(string s1, string s2){}
12     work(string nc, string s1, string s2){  }
13     string type = "work";
14 };
15     
16 class book:base{
17 public:
18     book(){}
19     string type = "book";
20 };
21     
22     
23 /**** important: begin *****/ 
24 
25 // return object of type 'work'
26 work set_class(string s1, string s2)
27 {
28     return work(s1,s2);
29 }
30 
31 
32 // return object of type 'T'; general program;
33 template<class T, class U>
34 T get_object(U ...)
35 {
36     return T();
37 }
38 
39 /**** important: end *****/ 
40 
41 // systhesis
42 void run()
43 {
44     string say = "object_type := ";
45     string s1="hello";
46     string s2="world";
47     cout << say << set_class(s1,s2).type << endl;
48     cout << say << get_object<work, string>(s1).type << endl;
49     cout << say << get_object<work, string>(s1,s2).type << endl;
50     cout << say << get_object<book>(1).type << endl;
51     cout << say << get_object<book>(1,2).type << endl;
52     cout << say << get_object<book>(1,2,3).type << endl;
53 }
54 
55 // test part; entrance
56 int main()
57 {
58     run();
59     return 0;    
60 }

 

 

 

二、运行结果

1 object_type := work
2 object_type := work
3 object_type := work
4 object_type := book
5 object_type := book
6 object_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