I am trying to use a map as a way to implement an object factory. In Python it is possible to store a class type in a map, and use it later to create objects from that type:
class Foo:
# ...
class Bar:
# ...
factory_map = { 'foo' : Foo, 'bar' : Bar }
foo_object = factory_map['foo']()
I am not aware of a similar feature (i.e., storing a type in a map) in C++, so I came up with a solution based on lambda functions where the map stores functions responsible to create the objects:
class Base {
public:
typedef std::unique_ptr<Base> Pointer;
virtual void hi() = 0;
};
class Foo : public Base {
public:
void hi() { std::cout << "Hi, it's foo\n"; }
};
class Bar : public Base {
public:
void hi() { std::cout << "Hi, it's bar\n"; }
};
int main() {
std::map<
std::string,
std::function<Base::Pointer()>> factory_map = {
{ "foo", []() { return Base::Pointer(new Foo()); } },
{ "bar", []() { return Base::Pointer(new Bar()); } },
};
Base::Pointer b1 = factory_map["foo"]();
b1->hi();
Base::Pointer b2 = factory_map["bar"]();
b2->hi();
}
This might be the most straightforward solution to obtain Python's simplicity. I am wondering, however, if the usage of lambdas is the best way to create the factory. Specifically, I would like to know what are the pros/cons of this approach compared to a more "traditional" factory design (i.e., one using if
/else
conditionals to decide the type of the object to create).