I want to create objects with polymorphic types based on a string I read from some config text file. A naive simple solution to this is to assign a string to each possible type and then compare the config string in an else-if chain to all the defined types. Something like:
class Base
{
virtual std::string GetStringType() = 0;
};
class Derived1 : public Base
{
std::string GetStringType() override { return "Derived1"; }
};
class Derived2 : public Base
{
std::string GetStringType() override { return "Derived2"; }
};
// etc ...
void main(int argc, char *argv[])
{
std::unique_ptr<Base> ptr;
auto derived1 = std::make_unique<Derived1>();
auto derived2 = std::make_unique<Derived2>();
// etc ...
std::string stringType(argv[1]);
if (stringType == derived1->GetStringType())
ptr = std::make_unique<decltype(derived1)>();
else if (stringType == derived2->GetStringType())
ptr = std::make_unique<decltype(derived2)>();
// etc ...
}
However, with this approach, each time a new derived class is added, a new else-if branch needs to be manually added, and I am trying to avoid that. Is there a better, more automatic approach to this?
Also, in an ideal scenario, when a new derived class is defined somewhere (just defined, not instantiated), I would like to check against it automatically also. Is this somehow possible? I'd be happy for any solution that works, macros included.