aboutsummaryrefslogtreecommitdiffstats
path: root/meowpp/oo/ObjSelector.h
blob: 58debcbea52aa36fd423a60ec19d61071d980c94 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#ifndef   oo_ObjSelector_H__
#define   oo_ObjSelector_H__

#include "ObjBase.h"

#include <cstdlib>

namespace meow{
  template<size_t id>
  class ObjSelector{
    private:
      typedef std::map   <std::string, ObjBase*> Funcs;
      typedef std::vector<std::string          > Types;
      //
      static Funcs& funcs(){
        static Funcs f;
        return f;
      }
      //
      std::string name;
      ObjBase*    ptr;
    public:
      ObjSelector(               ObjBase* o){ add(name = o->type(), ptr = o); }
      ObjSelector(std::string n, ObjBase* o){ add(name = n        , ptr = o); }
      ~ObjSelector(){ del(name); }
      //
      static void add(std::string n, ObjBase* b){
        del(n);
        funcs()[n] = b;
      }
      static void del(std::string s){
        if(funcs().find(s) != funcs().end()){
          delete funcs()[s];
          funcs().erase(s);
        }
      }
      static ObjBase const* access(std::string s){
        if(funcs().find(s) == funcs().end()) return NULL;
        return funcs()[s];
      }
      static ObjBase* get(std::string s){
        if(funcs().find(s) == funcs().end() || funcs()[s] == NULL)
          return NULL;
        return funcs()[s]->create();
      }
      static std::string find(ObjBase* o){
        for(Funcs::iterator it = funcs().begin(); it != funcs().end(); it++)
          if(it->second != NULL && it->second->type() == o->type()){
            return it->first;
          }
        return std::string();
      }
      static Types lst(){
        Types ret;
        for(Funcs::iterator it = funcs().begin(); it != funcs().end(); it++)
          ret.push_back(it->first);
        return ret;
      }
  };
}

#endif // oo_ObjSelector_H__