Skip to content

Instantly share code, notes, and snippets.

@dwburke
Last active July 9, 2024 15:40
Show Gist options
  • Save dwburke/c979cad57db82a43c4ce348e89fcafb9 to your computer and use it in GitHub Desktop.
Save dwburke/c979cad57db82a43c4ce348e89fcafb9 to your computer and use it in GitHub Desktop.
c++ factory
#include "Factory.h"
class SampleFactory : public Factory<sample_parent_class, std::string> {
public:
SampleFactory() {
registerType<smple_child_class>("child1");
};
};
SampleFactory sample_factory;
auto sample_thing = sample_factory.create("child1");
#include "Factory.h"
class ObjectTypeFactory : public Factory<object_type_generic, int, Object *> {
public:
ObjectTypeFactory() {
registerType<object_type_light>(OBJECT_WEAPON);
};
};
ObjectTypeFactory object_type_factory;
auto object = object_type_factory.create(type_id, this);
#pragma once
template <typename T, typename KEYT, typename... Args>
class Factory
{
public:
template <typename TDerived>
void registerType(KEYT key)
{
static_assert(std::is_base_of<T, TDerived>::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
_createFuncs[key] = &createFunc<TDerived>;
}
std::shared_ptr<T> create(KEYT key, Args... args) {
try {
auto f = _createFuncs.at(key);
return f(args...);
} catch (const std::out_of_range &) {
throw std::range_error(fmt::format("key [{}] is not registered", key));
}
}
private:
template <typename TDerived>
static std::shared_ptr<T> createFunc(Args... args)
{
return std::shared_ptr<TDerived>(new TDerived(args...));
}
typedef std::shared_ptr<T> (*PCreateFunc)(Args...);
std::map<KEYT, PCreateFunc> _createFuncs;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment