BARE2D
Cache_impl.tcc
Go to the documentation of this file.
1 #pragma once
2 // This holds all the non-specialized templates for Cache.hpp
3 
4 #include "BAREErrors.hpp"
5 
6 namespace BARE2D {
7 
8 template <typename S, typename T> T* Cache<S, T>::findItem(S& key)
9 {
10  // Check if we have the item in the m_data map
11 
12  auto iter = m_data.find(key);
13 
14  if(iter == m_data.end())
15  {
16  return nullptr;
17  } else
18  {
19  return m_data[key];
20  }
21 }
22 
23 template <typename S, typename T> T* Cache<S, T>::operator[](S& key)
24 {
25  return findItem(key);
26 }
27 
28 template <typename S, typename T> bool Cache<S, T>::addItem(S& key, T* item)
29 {
30  if(findItem(key))
31  return false;
32  m_data[key] = item;
33  return true;
34 }
35 
36 template <typename S, typename T> bool Cache<S, T>::setItem(S& key, T* item)
37 {
38  if(findItem(key))
39  {
40  delete findItem(key);
41  }
42  m_data[key] = item;
43  return true;
44 }
45 
46 template <typename S, typename T> T* Cache<S, T>::createItem(S& key, std::function<T*()> creationFunc)
47 {
48  // Creates an item, or overwrites the existing item if it already exists.
49 
50  // Check if it already exists
51  T* object = findItem(key);
52 
53  // nullptr if object doesn't already exist
54  if(object)
55  {
56  throwFatalError(BAREError::CACHE_FAILURE, "Item was created twice.");
57  return nullptr;
58  }
59 
60  // Now we know the object doesn't exist, so we need to create one!
61  object = creationFunc();
62 
63  m_data.insert(std::make_pair(key, object));
64 
65  return object;
66 }
67 
68 template <typename S, typename T> void Cache<S, T>::clear()
69 {
70  // Deletes all in m_data, then clears m_data.
71  // Delete em all
72  for(std::pair<S, T*> i : m_data)
73  {
74  delete i.second;
75  }
76 
77  // Clear it all
78  m_data.clear();
79 }
80 
81 template <typename S, typename T> unsigned int Cache<S, T>::getCount()
82 {
83  return m_data.size();
84 }
85 
86 template <typename S, typename T> typename std::unordered_map<S, T*>::iterator Cache<S, T>::begin()
87 {
88  return m_data.begin();
89 }
90 
91 template <typename S, typename T> typename std::unordered_map<S, T*>::iterator Cache<S, T>::end()
92 {
93  return m_data.end();
94 }
95 
96 template <typename S, typename T> bool Cache<S, T>::operator!=(Cache& other)
97 {
98  return m_data != other.m_data;
99 }
100 
101 } // namespace BARE2D