dungeon_crawler

view prototype/src/dataset.h @ 52:bcdea26c8f27

foo
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 18 Sep 2012 18:34:28 +0300
parents
children 7f52d6310317
line source
1 #ifndef DATASET_H_
2 #define DATASET_H_
4 #include <string.h>
5 #include <string>
6 #include <map>
7 #include <functional>
8 #include "datapath.h"
10 template <typename T>
11 class DataSet {
12 private:
13 mutable std::map<std::string, T> data;
15 std::function<T(const char*)> load;
16 std::function<void(T)> destroy;
18 public:
19 DataSet(std::function<T(const char*)> load_func, std::function<void(T)> destr_func);
20 ~DataSet();
22 T get(const char *name) const;
23 };
25 template <typename T>
26 DataSet<T>::DataSet(std::function<T(const char*)> load_func, std::function<void(T)> destr_func)
27 {
28 load = load_func;
29 destroy = destr_func;
30 }
32 template <typename T>
33 DataSet<T>::~DataSet()
34 {
35 if(destroy) {
36 for(auto it : data) {
37 destroy(it.second);
38 }
39 }
40 }
42 template <typename T>
43 T DataSet<T>::get(const char *name) const
44 {
45 auto iter = data.find(name);
46 if(iter != data.end()) {
47 return iter->second;
48 }
50 const char *path, *slash;
51 if((slash = strrchr(name, '/'))) {
52 path = slash + 1;
53 } else {
54 path = name;
55 }
56 if(!(path = datafile_path(path))) {
57 fprintf(stderr, "can't find data file: %s\n", name);
58 return 0;
59 }
61 T res = load(path);
62 if(res) {
63 data[name] = res;
64 }
65 return res;
66 }
68 #endif // DATASET_H_