1#ifndef DUNE_FEM_SINGLETON_HH
2#define DUNE_FEM_SINGLETON_HH
9#include <unordered_map>
21 class SingletonStorage
25 struct Item {
virtual ~Item() {} };
27 typedef std::shared_ptr< Item > WeakPointerType;
28 typedef std::unique_ptr< Item > PointerType;
29 typedef std::type_index KeyType;
31 typedef std::pair< std::unordered_map< KeyType, std::shared_ptr< Item > >, std::vector<PointerType> > StorageType;
35 struct SingletonDeleter
37 void operator()(StorageType* storage)
const
40 std::for_each(storage->second.rbegin(), storage->second.rend(),
41 [](PointerType& item) { item.reset(); });
43 storage->second.clear();
44 storage->first.clear();
49 typedef std::unique_ptr<StorageType, SingletonDeleter> StoragePointer;
52 static StoragePointer storage_;
55 static StorageType& getStorage()
59 storage_.reset(
new StorageType() );
69 template<
class Object >
72 typedef detail::SingletonStorage BaseType;
73 typedef typename BaseType::StorageType StorageType;
74 typedef typename BaseType::Item Item;
75 typedef typename BaseType::PointerType PointerType;
76 typedef typename BaseType::WeakPointerType WeakPointerType;
78 using BaseType::getStorage;
81 struct ItemWrapper :
public Item
84 template <
class... Args>
85 ItemWrapper(Args &&... args) : obj_(std::forward< Args >( args )...)
88 typedef ItemWrapper ItemWrapperType;
93 void operator()(Item *p)
const {}
100 template <
class... Args>
104 static Object& inst =
getObject(std::forward< Args >( args )...);
114 template <
class... Args>
120 static Object obj( std::forward< Args >( args )...);
126 StorageType& storage = getStorage();
129 auto& ptr = storage.first[ std::type_index(
typeid(Object)) ];
136 storage.second.emplace_back( PointerType(
new ItemWrapperType(std::forward< Args >( args )...) ) );
139 ptr = WeakPointerType( storage.second.back().operator->(), NullDeleter() );
143 assert(
dynamic_cast< ItemWrapperType*
> (ptr.operator->()) );
144 return static_cast< ItemWrapperType&
> (*ptr).obj_;
Definition: bindguard.hh:11
static bool singleThreadMode()
returns true if program is operating on one thread currently
Definition: threadmanager.hh:74
return singleton instance of given Object type.
Definition: singleton.hh:71
static Object & getObject(Args &&... args)
return singleton instance of given Object type.
Definition: singleton.hh:115
static Object & instance(Args &&... args)
return singleton instance of given Object type.
Definition: singleton.hh:101
static const bool placeStaticVariableInline
Definition: singleton.hh:110