Proton  1.1.1
Make porting easy from Python to C++11
_mapped_type.hpp
1 #ifndef PROTON_MAPPED_TYPE_HEADER
2 #define PROTON_MAPPED_TYPE_HEADER
3 
4 namespace proton{
5 
6 template <typename mapT, typename K>
7 typename mapT::mapped_type get(const mapT& x, K&& key)
8 {
9  auto it=x.find(key);
10  PROTON_THROW_IF(it==x.end(), "can't find the key in a map");
11  return it->second;
12 }
13 
14 template <typename mapT, typename K, typename V>
15 typename mapT::mapped_type get(const mapT& x, K&& key, V&& dft)
16 {
17  auto it=x.find(key);
18  if(it==x.end())
19  return dft;
20  return it->second;
21 }
22 
23 template <typename mapT, typename K>
24 bool test_get(typename mapT::mapped_type& v, const mapT& x, K&& key)
25 {
26  auto it=x.find(key);
27  if(it==x.end())
28  return false;
29  v=it->second;
30  return true;
31 }
32 
33 template <typename mapT, typename K, typename V>
34 bool test_insert(mapT& x, K&& k, V&& v)
35 {
36  return x.insert({k,v}).second;
37 }
38 
39 template <typename mapT, typename K, typename V>
40 bool test_insert_or_get(mapT& x, K&& k, V& v)
41 {
42  auto p=x.insert({k,v});
43  if(p.second)
44  return true;
45  v=p.first->second;
46  return false;
47 }
48 
49 template <typename mapT, typename K, typename ...argT>
50 typename mapT::mapped_type& get_or_create(bool& hit, mapT& x, K&& k, argT&& ... v)
51 {
52  auto p=x.find(k);
53  if(p!=x.end()){
54  hit= true;
55  return p->second;
56  }
57  hit=false;
58 #if 0
59  p=x.emplace(k, v...);
60 #else
61  p=x.insert({k,typename mapT::mapped_type(v...)}).first;
62 #endif
63  return p->second;
64 }
65 
66 }
67 
68 #endif // PROTON_MAPPED_TYPE_HEADER