Last change
on this file since 3 was
3,
checked in by epyon, 12 years ago
|
- common.hh - common defintions, platform/compiler/arch detection
- config.hh - compilation configuration
- exception.hh - exception root classes
- singleton.hh - templated singleton implementation
|
File size:
1.7 KB
|
Rev | Line | |
---|
[3] | 1 | // Copyright (C) 2012-2013 ChaosForge / Kornel Kisielewicz
|
---|
| 2 | // http://chaosforge.org/
|
---|
| 3 | //
|
---|
| 4 | // This file is part of NV Libraries.
|
---|
| 5 | // For conditions of distribution and use, see copyright notice in nv.hh
|
---|
| 6 |
|
---|
| 7 | /**
|
---|
| 8 | * @file singleton.hh
|
---|
| 9 | * @author Kornel Kisielewicz epyon@chaosforge.org
|
---|
| 10 | * @brief singleton pattern
|
---|
| 11 | */
|
---|
| 12 |
|
---|
| 13 | #ifndef NV_SINGLETON_HH
|
---|
| 14 | #define NV_SINGLETON_HH
|
---|
| 15 |
|
---|
| 16 | #include <cassert>
|
---|
| 17 |
|
---|
| 18 | namespace nv
|
---|
| 19 | {
|
---|
| 20 |
|
---|
| 21 | template <class T>
|
---|
| 22 | class singleton
|
---|
| 23 | {
|
---|
| 24 | private:
|
---|
| 25 | static T *singleton_;
|
---|
| 26 |
|
---|
| 27 | protected:
|
---|
| 28 | singleton()
|
---|
| 29 | {
|
---|
| 30 | assert(!singleton_);
|
---|
| 31 | singleton_ = static_cast<T*>(this);
|
---|
| 32 | }
|
---|
| 33 |
|
---|
| 34 | ~singleton()
|
---|
| 35 | {
|
---|
| 36 | assert(singleton_);
|
---|
| 37 | singleton_ = 0;
|
---|
| 38 | }
|
---|
| 39 |
|
---|
| 40 | public:
|
---|
| 41 | static bool is_valid()
|
---|
| 42 | {
|
---|
| 43 | return singleton_ != 0;
|
---|
| 44 | }
|
---|
| 45 | static T *pointer()
|
---|
| 46 | {
|
---|
| 47 | assert(singleton_);
|
---|
| 48 | return singleton_;
|
---|
| 49 | }
|
---|
| 50 | static T &reference()
|
---|
| 51 | {
|
---|
| 52 | assert(singleton_);
|
---|
| 53 | return *singleton_;
|
---|
| 54 | }
|
---|
| 55 | };
|
---|
| 56 |
|
---|
| 57 | template <class T>
|
---|
| 58 | T* singleton<T>::singleton_ = 0;
|
---|
| 59 |
|
---|
| 60 | template <class T>
|
---|
| 61 | class auto_singleton : public singleton<T>
|
---|
| 62 | {
|
---|
| 63 | public:
|
---|
| 64 | static T *pointer()
|
---|
| 65 | {
|
---|
| 66 | if ( !singleton<T>::is_valid() )
|
---|
| 67 | {
|
---|
| 68 | new T();
|
---|
| 69 | }
|
---|
| 70 | return singleton<T>::pointer();
|
---|
| 71 | }
|
---|
| 72 | static T &reference()
|
---|
| 73 | {
|
---|
| 74 | if ( !singleton<T>::is_valid() )
|
---|
| 75 | {
|
---|
| 76 | new T();
|
---|
| 77 | }
|
---|
| 78 | return singleton<T>::reference();
|
---|
| 79 | }
|
---|
| 80 | };
|
---|
| 81 |
|
---|
| 82 | } // namespace nv
|
---|
| 83 |
|
---|
| 84 | #endif // NV_SINGLETON_HH
|
---|
Note: See
TracBrowser
for help on using the repository browser.