[C++] STL源码中学到的 Traits 编程技法的应用

 代码如下:

 1 #include <map>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 namespace mapext
 6 {
 7     template <class T>
 8     struct type_traits
 9     {
10         typedef typename T* return_type;
11     };
12 
13     template <class T>
14     struct type_traits<T*>
15     {
16         typedef typename T* return_type;
17     };
18 
19     template<class T>
20     static typename T* FindOneItemValue(T& value)
21     {
22         return &value;
23     }
24 
25     template<class T>
26     static typename T* FindOneItemValue(T* value)
27     {
28         return value;
29     }
30 
31     template <class K, class T>
32     static typename type_traits<typename T::mapped_type>::return_type FindOneItem(K key, T& value)
33     {
34         T::iterator it = value.find(key);
35         if (it != value.end())
36         {
37 
38             return FindOneItemValue(it->second);
39         }
40         return nullptr;
41     };
42 }
43 
44 int main(int argc, char** argv)
45 {
46     std::map<int, int> num1;
47     std::map<int, int*> num2;
48 
49     num1.insert(make_pair(1, 1));
50     num2.insert(make_pair(1, new int(1)));
51 
52     int* pn1 = mapext::FindOneItem(1, num1);
53     int* pn2 = mapext::FindOneItem(1, num2);
54 
55     return 0;
56 }

 

 

无需赘述,一切尽在源码中,请用心领会。

posted @ 2021-10-29 20:38  dilex  阅读(56)  评论(0编辑  收藏  举报