First of all, the syntax primer:
struct Base { virtual ~Base() {}
Then the "factory" function:
template <typename T> std::unique_ptr<Base> makeBase() { return std::unique_ptr<Base>(new T{}); }
Type of this function:
using BaseMaker = std::unique_ptr<Base>(*)();
And finally putting it at all:
struct DerivedOne: Base {}; struct DerivedTwo: Base {}; using BaseMakerMap = std::map<std::string, BaseMaker>; BaseMakerMap const map = { { "DerivedOne", makeBase<DerivedOne> }, { "DerivedTwo", makeBase<DerivedTwo> } }; std::unique_ptr<Base> makeFromName(std::string const& n) { BaseMakerMap::const_iterator it = map.find(n); if (it == map.end()) { return std::unique_ptr<Base>(); }
source share