Hey, I'm working on a project incorporating runtim e modules. Several class interfaces are given which are then loaded dynamically. The library doesn't need to know about any of these classes except a few which are needed by the library. The only trouble is actually accessing these classes. Since the types are not known at compile time, the factory pattern comes to mind but it doesn't quite work as well as I'd expect (First time I really looked into it though, something might have slipped my attention).
The whole program as a library is designed to run in so-called instances and has no global variables at all. Even though it's unlikely, each instance has its own modules and thus needs to have its own factories (or constructor methods). The way I implemented it for now is:
Code:
class Instance {
// ...
// I have a macro for this stuff
Type *(*NewType)(Instance *i, ...);
};
Type *(Instance::NewType)(Instance *i, ...) = NULL;
Then there are macros for loading a module by providing a creator function.
This solution seems rather messy to me. Is there any way to make this work without resorting to macros and name concatenation? The catch is that different constructors may need different arguments so a template function would not work. Also it's function pointers I need, not functions.
The ideal way would be to call
Code:
Type *obj = instance->New<Type>(instance, args);
but that would require template variables and is not possible, am I right?
PS: Since modules are likely to depend on each other, is there any way to check if certain implementations (classes) are present without relying on name checking such as "if (ModuleLoaded(name)) ..."? Dynamic library are really fragile things and I don't want the whole thing to crash because module A is replaced by A' which is something else. A way to register provided classes and define their interfaces would be great although that might be a bit tedious for library development. If done right however the project itself could use the same mechanism, making it even more generic. Any ideas?