Simulant  21.12-574
A portable game engine for Windows, OSX, Linux, Dreamcast, and PSP
data_carrier.h
1 /* * Copyright (c) 2011-2017 Luke Benstead https://simulant-engine.appspot.com
2  *
3  * This file is part of Simulant.
4  *
5  * Simulant is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * Simulant is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public License
16  * along with Simulant. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #ifndef USER_DATA_CARRIER_H
20 #define USER_DATA_CARRIER_H
21 
22 #include <unordered_map>
23 #include <string>
24 #include <stdexcept>
25 
26 #include "any/any.h"
27 
28 namespace smlt {
29 namespace generic {
30 
31 class NoSuchData : public std::runtime_error {
32 public:
33  NoSuchData(const std::string& what):
34  std::runtime_error(what) {}
35 };
36 
37 class DataCarrier {
38 public:
39  virtual ~DataCarrier() {}
40 
41  template<typename T>
42  void stash(T thing, const std::string& identifier) {
43  things_[identifier] = smlt::any(thing);
44  }
45 
46  bool exists(const std::string& identifier) const {
47  return things_.count(identifier);
48  }
49 
50  template<typename T>
51  T get(const std::string& identifier) const {
52  if(!exists(identifier)) {
53  throw NoSuchData(identifier);
54  }
55  return smlt::any_cast<T>(things_.at(identifier));
56  }
57 
58  void unstash(const std::string& identifier) {
59  if(!exists(identifier)) return;
60 
61  things_.erase(identifier);
62  }
63 
64 private:
65  std::unordered_map<std::string, smlt::any> things_;
66 };
67 
68 }
69 }
70 
71 #endif // USER_DATA_CARRIER_H
smlt::v1::any
Definition: any.h:127
smlt
Definition: animation.cpp:25
smlt::generic::DataCarrier
Definition: data_carrier.h:37
smlt::generic::NoSuchData
Definition: data_carrier.h:31