summaryrefslogtreecommitdiff
path: root/engine-ocean/Game/TypeMap.h
blob: add336737c5c800f1fb1b3eeaabf17af3b237d90 (plain)
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
#ifndef TYPEMAP_H
#define TYPEMAP_H
#include <unordered_map>
#include <atomic>

template <class ValueType>
class TypeMap {
    typedef std::unordered_map<int, ValueType> InternalMap;

public:
    typedef typename InternalMap::iterator iterator;
    typedef typename InternalMap::const_iterator const_iterator;
    typedef typename InternalMap::value_type value_type;

    const_iterator begin() const { return m_map.begin(); }
    const_iterator end() const { return m_map.end(); }

    iterator begin() { return m_map.begin(); }
    iterator end() { return m_map.end(); }

    // finds the value associated with type "Key" in the typemap
    template <class Key>
    iterator find() { return m_map.find(getTypeId<Key>()); }

    template <class Key>
    const_iterator find() const { return m_map.find(getTypeId<Key>()); }

    template <class Key>
    bool contains() { return m_map.count(getTypeId<Key>()); }

    // associates a value with the type "Key"
    template <class Key>
    void put(ValueType &&value){
        m_map[getTypeId<Key>()] = std::forward<ValueType>(value);
    }

    template <class Key>
    void remove() { m_map.erase(getTypeId<Key>()); }

private:
    template <class Key>
    inline static int getTypeId(){
        static const int id = LastTypeId++;
        return id;
    }

    static std::atomic_int LastTypeId;
    InternalMap m_map;
};

template <class ValueType>
std::atomic_int TypeMap<ValueType>::LastTypeId(0);

#endif // TYPEMAP_H