Sauce-0.10.1
A C++ Dependency Injection Framework
scope_cache.h
1#ifndef SAUCE_INTERNAL_SCOPE_CACHE_H_
2#define SAUCE_INTERNAL_SCOPE_CACHE_H_
3
4#include <sauce/internal/key.h>
5#include <sauce/internal/type_id.h>
6
7namespace sauce {
8namespace internal {
9
10template<typename Dependency>
12public:
13 typedef typename Key<Dependency>::Ptr SmartPtr;
14 void operator()(void * smartPtrPtr) const {
15 delete static_cast<SmartPtr *>(smartPtrPtr);
16 }
17};
18
20 typedef sauce::shared_ptr<void> CachedPtr;
21 typedef std::map<TypeId, CachedPtr> Cache;
22
23 Cache cache;
24
25public:
26
27 ScopeCache():
28 cache() {}
29
33 template<typename Dependency>
34 void put(typename Key<Dependency>::Ptr pointer) {
35 typedef typename Key<Dependency>::Normalized Normalized;
36 typedef typename Key<Normalized>::Ptr SmartPtr;
37
38 /*
39 * A voice! a voice! It rang deep to the very last. It survived his strength to hide in the
40 * magnificent folds of eloquence the barren darkness of his heart. Oh, he struggled! he
41 * struggled! The wastes of his weary brain were haunted by shadowy images now – images of
42 * wealth and fame revolving obsequiously round his unextinguishable gift of noble and lofty
43 * expression. My Intended, my station, my career, my ideas – these were the subjects for the
44 * occasional utterances of elevated sentiments.
45 */
46
47 /*
48 * (Make the new smart ptr type agnostic by shoving it into *another* smart pointer.
49 * The deleter casts it back so the reference count isn't leaked.)
50 */
51
52 CachedPtr cachedPtr(
53 static_cast<void *>(new SmartPtr(pointer)),
55
56 cache.insert(std::make_pair(typeIdOf<Normalized>(), cachedPtr));
57 }
58
65 template<typename Dependency>
66 bool get(typename Key<Dependency>::Ptr & out) const {
67 typedef typename Key<Dependency>::Normalized Normalized;
68 typedef typename Key<Normalized>::Ptr SmartPtr;
69
70 Cache::const_iterator cachedPtr = cache.find(typeIdOf<Normalized>());
71 if (cachedPtr == cache.end()) {
72 return false;
73 }
74
75 out = *static_cast<SmartPtr *>(cachedPtr->second.get());
76 return true;
77 }
78};
79
80}
81
82namespace i = ::sauce::internal;
83
84}
85
86#endif // SAUCE_INTERNAL_SCOPE_CACHE_H_
A complete specification of a dependency request.
Definition: key.h:15
Definition: scope_cache.h:19
void put(typename Key< Dependency >::Ptr pointer)
Insert a dependency into the cache.
Definition: scope_cache.h:34
bool get(typename Key< Dependency >::Ptr &out) const
Probe the cache for a dependency.
Definition: scope_cache.h:66
Definition: scope_cache.h:11