Here are some subclasses that derive from the abstract class:
class obj
{
public:
virtual std::string type() = 0;
};
class subobj01 : public obj
{
public:
std::string type() override
{
return "subobj01";
}
};
class subobj02 : public obj
{
public:
std::string type() override
{
return "subobj02";
}
};
class subobj03 : public obj
{
public:
std::string type() override
{
return "subobj03";
}
};
Now I want to define a function that does the following,
// pseudo-code
type create_instance(std::shared_ptr<obj> o)
{
if (o->type() == "subobj01")
return std::make_shared<subobj01>();
else if (o->type() == "subobj02")
return std::make_shared<subobj02>();
else if (o->type() == "subobj03")
return std::make_shared<subobj03>();
}
I don't know if this can be achieved using template metaprogramming. Thanks!
Update:
I know I can use std::dynamic_pointer_cast
to convert pointers manually.
In fact, obj
and subobjxxx
are defined by third-party libraries (I shouldn't modify them). I just want to implement a wrapper to do the pointer conversion automatically, without manually specifying the type.