Last active
August 29, 2015 14:04
-
-
Save Jules-Baratoux/f81e55e0e7d22716db43 to your computer and use it in GitHub Desktop.
A wrapper turning any class into a statically allocated singleton constructed at first use.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct object | |
{ | |
int attr; | |
// disable the object construction outside of the singleton | |
private: | |
object() {} | |
friend singleton<object>; | |
}; | |
instantiate_singleton_template(object); | |
int main(void) | |
{ | |
object& first = singleton<object>(); | |
first.attr = 42; | |
object& second = singleton<object>(); | |
assert( second.attr == 42 ); | |
assert( &first == &second ); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <stdint.h> | |
#include <stddef.h> | |
#include <new> | |
template <typename T, typename byte = uint8_t> | |
class singleton | |
{ | |
typedef T*(function)(void); | |
typedef byte memory[sizeof(T) / sizeof(byte)]; | |
static memory block; | |
static T* pointer; | |
static function* proxy; | |
static inline T* access(void) | |
{ | |
return pointer; | |
} | |
static inline T* init(void) | |
{ | |
pointer = new (&block) T; | |
proxy = &access; | |
} | |
public: | |
singleton(void) | |
{ | |
proxy(); | |
} | |
inline operator T& (void) const | |
{ | |
return *proxy(); | |
} | |
}; | |
#define instantiate_singleton_template(T) \ | |
template<> \ | |
T* singleton<T>::pointer = NULL; \ | |
\ | |
template<> \ | |
singleton<T>::function* \ | |
singleton<T>::proxy = &singleton<T>::init; \ | |
\ | |
template<> \ | |
singleton<T>::memory \ | |
singleton<T>::block = {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment