假设我有一个std::any
对象,它可能包含也可能不包含指向给定基类的某个派生类的指针B
。有什么办法可以做到:
B *
如果std::any
对象包含可转换为 的东西,则返回 aB *
,或- 如果没有抛出异常?
似乎每个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);
}
I don't want to include a bunch of boilerplate code listing every single kind of saw in existence just so I can grab a saw -- any Saw
-- to use in Factory1
.