假設字符串在運行時只知道,是否可以建立類的層次結構,最簡單的選項,以建立地圖的工廠功能的使用多態和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