sftools  2.0 dev
Bunch of tools for SFML application development
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Pages
GenericManager.tpp
Go to the documentation of this file.
1 /*
2 
3  sftools - Copyright (c) 2012-2013 Marco Antognini <antognini.marco@gmail.com>
4 
5  This software is provided 'as-is', without any express or implied warranty. In
6  no event will the authors be held liable for any damages arising from the use
7  of this software.
8 
9  Permission is granted to anyone to use this software for any purpose, including
10  commercial applications, and to alter it and redistribute it freely, subject to
11  the following restrictions:
12 
13  1. The origin of this software must not be misrepresented; you must not claim
14  that you wrote the original software. If you use this software in a product,
15  an acknowledgment in the product documentation would be appreciated but is
16  not required.
17 
18  2. Altered source versions must be plainly marked as such, and must not be
19  misrepresented as being the original software.
20 
21  3. This notice may not be removed or altered from any source distribution.
22 
23  */
24 
30 #include <stdexcept> // std::invalid_argument
31 
36 namespace sftools
37 {
38  template <typename Resource, typename Id, typename OnLoad>
40  : m_onLoad(OnLoad())
41  {
42  }
43 
44  template <typename Resource, typename Id, typename OnLoad>
45  bool GenericManager<Resource, Id, OnLoad>::load(Id const& id, bool forceReload)
46  {
47  // Already loaded ?
48  if (m_resources.count(id) != 0)
49  {
50  if (!forceReload)
51  {
52  // Don't do it twice!
53  return true;
54  }
55  else
56  {
57  unload(id);
58  }
59  }
60 
61  // No ? Ok, let my onLoad method do it.
62  ResourcePtr ptr = m_onLoad(id);
63 
64  // Was it correctly loaded ?
65  if (ptr)
66  {
67  m_resources[id] = ptr;
68 
69  return true;
70  }
71  else
72  {
73  return false;
74  }
75  }
76 
77  template <typename Resource, typename Id, typename OnLoad>
79  {
80  delete m_resources[id];
81  m_resources.erase(id);
82  }
83 
84  template <typename Resource, typename Id, typename OnLoad>
86  {
87  for (MapIterator it = m_resources.begin(); it != m_resources.end(); ++it)
88  {
89  delete it->second;
90  }
91  m_resources.clear();
92  }
93 
94  template <typename Resource, typename Id, typename OnLoad>
95  Resource const& GenericManager<Resource, Id, OnLoad>::operator[](Id const& id) const
96  {
97  MapConstIterator it = m_resources.find(id);
98 
99  if (it != m_resources.end())
100  {
101  return *it->second;
102  }
103  else
104  {
105  throw std::invalid_argument("Resource not loaded");
106  }
107  }
108 
109  template <typename Resource, typename Id, typename OnLoad>
111  {
112  MapIterator it = m_resources.find(id);
113 
114  if (it != m_resources.end())
115  {
116  return *it->second;
117  }
118  else
119  {
120  throw std::invalid_argument("Resource not loaded");
121  }
122  }
123 }