Last active
June 8, 2018 09:22
-
-
Save NicholasRoge/c2cfe93da6b265593201 to your computer and use it in GitHub Desktop.
C++11 Compliant Callback for Instantiation of Specified Types
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
#include <functional> | |
#include <vector> | |
#define snew NOTIFIER = new | |
/* Type Declarations */ | |
template<typename Type> | |
class InstantiationObserver | |
{ | |
friend class InstantiationNotifier; | |
public: | |
using InstantiationAction = std::function<void(Type*)>; | |
/* Class Properties */ | |
private: | |
static std::vector<InstantiationAction> actions; | |
/* Class Methods */ | |
private: | |
static void Notify(Type* instance); | |
public: | |
static void AddInstantiationAction(InstantiationAction action); | |
/* Member Methods */ | |
private: | |
InstantiationObserver(); | |
}; | |
template<typename Type> | |
void InstantiationObserver<Type>::Notify(Type* instance) | |
{ | |
for(auto action : InstantiationObserver<Type>::actions) | |
{ | |
action(instance); | |
} | |
} | |
class InstantiationNotifier | |
{ | |
/* Member Methods */ | |
public: | |
InstantiationNotifier(); | |
template<typename Type> | |
Type* operator =(Type* instance); | |
} | |
NOTIFIER; | |
/* Main */ | |
int main() | |
{ | |
unsigned* power_level; | |
InstantiationObserver<unsigned>::AddInstantiationAction([](unsigned* instance){ | |
*instance = 9001; | |
}); | |
power_level = snew unsigned(100); | |
if(*power_level == 9001) | |
{ | |
return 0; | |
} | |
else | |
{ | |
return 1; | |
} | |
} | |
/* Type Definitions */ | |
template<typename Type> | |
std::vector<typename InstantiationObserver<Type>::InstantiationAction> InstantiationObserver<Type>::actions; | |
template<typename Type> | |
void InstantiationObserver<Type>::AddInstantiationAction(typename InstantiationObserver<Type>::InstantiationAction action) | |
{ | |
InstantiationObserver<Type>::actions.push_back(action); | |
} | |
__InstantiationNotifier__::__InstantiationNotifier__() | |
{ | |
} | |
template<typename Type> | |
Type* __InstantiationNotifier__::operator =(Type* instance) | |
{ | |
InstantiationObserver<Type>::Notify(instance); | |
return instance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Forgot that identifiers starting with underscores were reserved, thus making the code not compliant. Thanks to reddit's /u/00kyle00 for pointing that out.