有什么方法可以在不知道派生类型的情况下,将包含派生指针的std :: any转换为基本指针?

Dan*_*ury 8 c++ stdany

假设我有一个std::any对象,该对象可能包含也可能不包含指向给定基类的某些派生类的指针B。有什么办法可以做些什么:

  1. B *如果std::any对象包含可转换为的内容,则返回B *,或者返回
  2. 如果没有抛出异常?

似乎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

eer*_*ika 6

这是无法实现的。只能std::any使用放入其中的类型来获取对象。因此,您必须知道类型才能从中获取任何内容。

似乎std::any不适合您的用例。