1#ifndef DUNE_FEM_SINGLETON_HH
2#define DUNE_FEM_SINGLETON_HH
10#include <unordered_map>
13#include <dune/common/visibility.hh>
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;
34 public std::pair< std::unordered_map< KeyType, std::shared_ptr< Item > >, std::vector<PointerType> >
37 std::pair<
std::unordered_map< KeyType,
std::shared_ptr< Item > >,
std::vector<PointerType> > (),
42 typedef std::recursive_mutex mutex_t;
46 typedef Storage StorageType;
50 struct SingletonDeleter
52 void operator()(StorageType* storage)
const
55 std::for_each(storage->second.rbegin(), storage->second.rend(),
56 [](PointerType& item) { item.reset(); });
58 storage->second.clear();
59 storage->first.clear();
64 typedef std::unique_ptr<StorageType, SingletonDeleter> StoragePointer;
67 static StoragePointer storage_;
70 DUNE_EXPORT
static StorageType& getStorage()
76 storage_.reset(
new StorageType() );
86 template<
class Object >
89 typedef detail::SingletonStorage BaseType;
90 typedef typename BaseType::StorageType StorageType;
91 typedef typename BaseType::Item Item;
92 typedef typename BaseType::PointerType PointerType;
93 typedef typename BaseType::WeakPointerType WeakPointerType;
95 using BaseType::getStorage;
98 struct ItemWrapper :
public Item
101 template <
class... Args>
102 ItemWrapper(Args &&... args) : obj_(std::forward< Args >( args )...)
105 typedef ItemWrapper ItemWrapperType;
110 void operator()(Item *p)
const {}
117 template <
class... Args>
118 DUNE_EXPORT
static Object&
instance(Args &&... args)
122 static thread_local Object& inst =
getObject(std::forward< Args >( args )...);
132 template <
class... Args>
138 static Object obj( std::forward< Args >( args )...);
146 StorageType& storage = getStorage();
150 std::lock_guard< StorageType::mutex_t > guard( storage.mutex_ );
153 auto& ptr = storage.first[ std::type_index(
typeid(Object)) ];
158 storage.second.emplace_back( PointerType(
new ItemWrapperType(std::forward< Args >( args )...) ) );
161 ptr = WeakPointerType( storage.second.back().operator->(), NullDeleter() );
165 assert(
dynamic_cast< ItemWrapperType*
> (ptr.operator->()) );
166 return static_cast< ItemWrapperType&
> (*ptr).obj_;
Definition: bindguard.hh:11
return singleton instance of given Object type.
Definition: singleton.hh:88
static DUNE_EXPORT Object & instance(Args &&... args)
return singleton instance of given Object type.
Definition: singleton.hh:118
static DUNE_EXPORT Object & getObject(Args &&... args)
return singleton instance of given Object type.
Definition: singleton.hh:133
static const bool placeStaticVariableInline
Definition: singleton.hh:128