zoukankan      html  css  js  c++  java
  • [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 }

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

  • 相关阅读:
    mysql--表数据的操作
    mysql--增删改查
    mysql--约束条件
    Mysql--基本配置
    Mysql--数据表
    Mysql--数据库的操作
    位运算的应用
    读书笔记--模板与泛型编程
    读书笔记六
    读书笔记五
  • 原文地址:https://www.cnblogs.com/dilex/p/15483419.html
Copyright © 2011-2022 走看看