Skip to content

Instantly share code, notes, and snippets.

@mathewmariani
Last active February 22, 2017 23:50
Show Gist options
  • Save mathewmariani/b66737814f1c43f2d87ee91baa4af88c to your computer and use it in GitHub Desktop.
Save mathewmariani/b66737814f1c43f2d87ee91baa4af88c to your computer and use it in GitHub Desktop.
Subsystem Registration/Initialization
#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;
}
#include "module.h"
Module *Module::instances[] = {};
void Module::registerModule(Module* instance) {
auto type = instance->getModuleType();
// NOTE: warn for overwritting
instances[type] = instance;
}
#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