假设我有一个std::any对象,该对象可能包含也可能不包含指向给定基类的某些派生类的指针B。有什么办法可以做些什么:
B *如果std::any对象包含可转换为的内容,则返回B *,或者返回似乎dynamic_cast并且std::any_cast每个都提供了此功能的一半,但是我看不到将两者结合在一起的任何方法。
我知道我可以通过多种方式来完成这项工作,包括显式枚举可转换为的每种类型B *,但这是所有DRY违规行为的源泉。
示例用例:
std::vector<std::any> setupTools(const std::string & confFile)
{
std::vector<std::any> myTools;
auto conf = parse(confFile);
for(std::string & wrenchInfo : conf["Wrenches"])
{
Wrench::setup(myTools, wrenchInfo);
}
for(std::string & hammerInfo : conf["Hammers"])
{
Hammer::setup(myTools, hammerInfo);
}
// 25 more kinds of tools
}
Factory1::init(const std::vector<std::any> & tools)
{
m_wrench = any_get<Wrench *>(tools);
m_hammer = any_get<Hammer *>(tools);
m_saw = any_get<Saw *>(tools);
}
Factory2::init(const std::vector<std::any> & tools)
{
m_wrench = any_get<TorqueWrench *>(tools);
}
Factory3::init(const std::vector<std::any> & tools)
{
m_saw = any_get<CordlessReciprocatingSaw *>(tools);
}
Run Code Online (Sandbox Code Playgroud)
我不想包含一堆样板代码列出现有的每种锯子,只是为了抓住我可以使用的任何 一种锯子。SawFactory1