假设字符串在运行时只知道,是否可以建立类的层次结构,最简单的选项,以建立地图的工厂功能的使用多态和std::function
:
鉴于.. 。
struct Base
{
virtual ~Base() { }
};
struct Derived0 : Base { };
struct Derived1 : Base { };
// ...
...你可以有...
std::map<std::string, std::function<std::unique_ptr<Base>>> map;
map["derived0"] = []{ return std::make_unique<Derived0>(); };
map["derived1"] = []{ return std::make_unique<Derived1>(); };
// ...
...可以使用如下:
std::string desiredType;
std::cin >> desiredType;
auto result = map[desiredType]();
注意,这种设计通常是代码味道。仔细考虑你想达到的目标 - 可能会有更清洁/更优雅的方式。
此外,使用std::unique_ptr
和std::function
可能会在您的应用程序中引入明显的开销。
听起来像多态的情况。 – NathanOliver
多态性或如果类不相关,那么也许'std :: any'。 –
看起来像不好的设计,解释你想要达到的效果 – Slava