-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimplCache.h
92 lines (75 loc) · 2 KB
/
SimplCache.h
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#pragma once
#include <unordered_map>
#include <memory>
#include "is_shared_ptr.h"
template<typename Key, typename Type>
class SimplCache_T
{
private:
typedef typename std::unordered_map<Key, Type>::iterator CacheIterator;
std::unordered_map<Key, Type> cache;
#ifdef _WIN32
template <bool> struct selectFn {};
typedef selectFn<true> TrueCond;
typedef selectFn<false> FalseCond;
void PutByKeyInternal(Type& value, TrueCond)
{
cache.insert(std::make_pair(value->GetKey(), value));
}
void PutByKeyInternal(Type& value, FalseCond)
{
cache.insert(std::make_pair(value.GetKey(), value));
}
#endif
public:
SimplCache_T() = default;
SimplCache_T(const SimplCache_T&) = delete;
SimplCache_T(SimplCache_T&&) = delete;
SimplCache_T& operator=(const SimplCache_T&) = delete;
void ClearAll()
{
cache.clear();
}
CacheIterator begin()
{
return cache.begin();
}
CacheIterator end()
{
return cache.end();
}
bool GetByKey(const Key& key, Type& value)
{
auto iter = cache.find(key);
if (iter == cache.end())
return false;
value = iter->second;
return true;
}
#ifdef _WIN32
// Using tag dispatch pattern instead
//http://stackoverflow.com/questions/6917079/tag-dispatch-versus-static-methods-on-partially-specialised-classes
void PutByKey(Type& value)
{
PutByKeyInternal(value, selectFn<is_shared_ptr<Type>::value>());
}
#else
// SFINAE below works perfectly fine for linux but as usual MSVC fails to understand that...
template <typename U = Type>
typename std::enable_if<!is_shared_ptr<U>::value, void>::type PutByKey(U& value)
{
cache.insert(std::make_pair(value.GetKey(), value));
}
template <typename U = Type>
typename std::enable_if<is_shared_ptr<U>::value, void>::type PutByKey(U& value)
{
cache.insert(std::make_pair(value->GetKey(), value));
}
#endif
unsigned int size()
{
return cache.size();
}
};
template <typename T>
using SimplCache = SimplCache_T<std::string, T>;