OK, here's one solution (it was raining outside so what the hell ):
It uses templates hevily, so you'll need a relatively updated compiler (I used MSVC++)
Here's the base code:
Code:
#include <vector>
#include <iostream>
#include <string>
#include <map>
#include <typeinfo>
//
// The base class for all modules
//
class Module
{
public:
virtual void someModuleThings()
{
}
};
//
// DeepBlackMagic's Core class
//
typedef Module* (*ModuleCreator)();
class Core
{
public:
static addModule(std::string name, ModuleCreator creator)
{
std::cout << "addModule(" << name << "," << creator << ")\n";
if (!moduleMap)
moduleMap = new std::map<std::string, ModuleCreator>();
(*moduleMap)[name] = creator;
}
static Module* newObject(std::string name)
{
if (!moduleMap)
moduleMap = new std::map<std::string, ModuleCreator>();
if ((*moduleMap)[name])
return (*moduleMap)[name]();
else
return 0;
}
protected:
static std::map<std::string, ModuleCreator>* moduleMap;
};
//Create the static member
std::map<std::string, ModuleCreator>* Core::moduleMap = 0;
//
// This class adds class M to the list of modules on
// creation
//
template <class M>
class ModuleCreatorClass
{
public:
ModuleCreatorClass()
{
//Add this module to the list of modules in Core
Core::addModule(typeid(M).name(), createThisModule);
}
//This function create a new M module
static Module* createThisModule()
{
return new M;
}
};
//
// This function creates an object of class C
// on instantiation
//
//
// This is the class that new modules should
// inherit from
//
template <class C>
class NewModule:
public Module
{
public:
NewModule()
{
//Must reference the static object here
//so it's instantiated.
&obj;
}
static ModuleCreatorClass<C> obj;
};
template <class C>
ModuleCreatorClass<C> NewModule<C>::obj;
To be continued...