Advertisement
sveta_t

Untitled

Oct 1st, 2014
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. template <typename Key, typename Value>
  2. class Proxy
  3. {
  4.     std::map<Key, Value>& my_map_;
  5.     Key key_;
  6. public:
  7.  
  8.     Proxy(std::map<Key, Value>& my_map, const Key& key) : my_map_(my_map), key_(key)
  9.     {
  10.     }
  11.  
  12.     operator Value()
  13.     {
  14.         std::cout << "Value()\n";
  15.         if (my_map_.find(key_) == std::end(my_map_))
  16.             return 0;
  17.         return my_map_[key_];
  18.     }
  19.  
  20.     const Value& operator=(const Value& value)
  21.     {
  22.         std::cout << "operator=\n";
  23.         return my_map_[key_] = value;
  24.     }
  25. };
  26.  
  27. template <typename Key, typename Value>
  28. class A
  29. {
  30.     std::map<Key, Value> my_map_;
  31. public:
  32.     Proxy<Key, Value> operator[](const Key& key)
  33.     {
  34.         return Proxy<Key, Value>(my_map_, key);
  35.     }
  36.  
  37.     const Value& operator[](const Key& key) const
  38.     {
  39.         std::cout << "const operator[]\n";
  40.         auto found = my_map_.find(key);
  41.         if (found == std::end(my_map_))
  42.             return 0;
  43.         return (found->second);
  44.     }
  45.  
  46.     void Print() const
  47.     {
  48.         std::cout << "Map content:\n";
  49.         for (auto const& it : my_map_)
  50.         {
  51.             std::cout << it.first << " " << it.second << "\n";
  52.         }
  53.     }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement