#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
class Base
{
public:
//...
virtual int getId() const = 0;
};
class Derived1: public Base
{
public:
//...
int getId() const override { return 0; }
};
class Derived2: public Base
{
public:
//...
int getId() const override { return 1; }
};
//...
using createFunc = std::shared_ptr<Base>(*)();
static std::map<int, createFunc> myMap
{
{0, []() -> std::shared_ptr<Base> { return std::make_shared<Derived1>(); }},
{1, []() -> std::shared_ptr<Base> { return std::make_shared<Derived2>(); }}
//...
};
static std::shared_ptr<Base> createInstance(int id)
{
auto iter = myMap.find(id);
if (iter == myMap.end())
throw std::out_of_range("Unknown id");
return iter->second();
}
static int getId(Base* instance)
{
return instance->getId();
}
int main()
{
auto inst1 = createInstance(0);
std::cout << getId(inst1.get()) << std::endl;
auto inst2 = createInstance(1);
std::cout << getId(inst2.get()) << std::endl;
try
{
auto inst3 = createInstance(3);
std::cout << getId(inst3.get()) << std::endl;
}
catch (const std::exception &e)
{
std::cout << e.what() << std::endl;
}
return 0;
}