A header-only cpp factory with a convenient MACRO to register classes.
It comes extremely handy and convenient with supports for dynamic libs.
Simply copy factory/Factory.hpp
to your project.
C++14 or above, for std::make_unique
. You can replace it with uglier old style code for compatibility.
Will use the code in example
to explain its usage.
- define your factory
namespace base {
using AnimalFactory = yy::StaticFactory<Animal, int, std::string>;
} /* base */
- register class with its name
namespace pet {
REGISTER_OBJECT(base::AnimalFactory, Cat);
REGISTER_OBJECT(base::AnimalFactory, Dog);
} /* pet */
- create instance with class name
auto cat = base::AnimalFactory::factory().create("Cat", 1, "kitty");
-
In your dynamic lib, you need to expose the factory with a C-function to avoid mangling
-
In your executable, load the symbol of the C-function you defined, and
merge
the result
Example:
extern "C"
{
// This is to expose all registered classes of a dynamic library
const auto& AnimalRegistry()
{
return AnimalRegistry::factory().registry();
}
}