Last active
February 22, 2017 23:50
-
-
Save mathewmariani/b66737814f1c43f2d87ee91baa4af88c to your computer and use it in GitHub Desktop.
Subsystem Registration/Initialization
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 <iostream> | |
#include "module.h" | |
class MyModule : public Module { | |
DECLARE_MODULE(Module::M_TYPE_ONE); | |
public: | |
MyModule() {} | |
}; | |
REGISTER_MODULE(MyModule); | |
int main() { | |
printf("Hello, World\n"); | |
return 0; | |
} |
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 "module.h" | |
Module *Module::instances[] = {}; | |
void Module::registerModule(Module* instance) { | |
auto type = instance->getModuleType(); | |
// NOTE: warn for overwritting | |
instances[type] = instance; | |
} |
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 | |
#define DECLARE_MODULE(type) \ | |
public: \ | |
ModuleType getModuleType() const final { return type; } | |
#define REGISTER_MODULE(className) \ | |
namespace { \ | |
Module* __CreateModule##className() { \ | |
return new className(); \ | |
} \ | |
class __register##className { \ | |
public: \ | |
__register##className() { \ | |
Module::registerModule(__CreateModule##className()); \ | |
} \ | |
}; \ | |
__register##className __g_instance##className; \ | |
} | |
class Module { | |
public: | |
enum ModuleType { | |
M_TYPE_ONE, | |
M_COUNT, | |
}; | |
public: | |
// NOTE: this causes memory leaks. | |
// Either use std::unique_ptr or handle destruction of pointers in instances[] | |
virtual ~Module() {} | |
virtual ModuleType getModuleType() const = 0; | |
static void registerModule(Module* instance); | |
private: | |
static Module* instances[M_COUNT]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment