从动态类型信息创建新对象

新手上路,请多包涵

在 C++ 中,有没有办法查询对象的类型,然后使用该信息动态创建相同类型的新对象?

例如,假设我有一个简单的 3 类层次结构:

 class Base
class Foo : public Base
class Bar : public Base

现在假设我给你一个转换为 Base 类型的对象——它实际上是 Foo 类型。有没有办法查询类型并使用该信息稍后创建 Foo 类型的新对象?

原文由 Daniel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 358
1 个回答

克隆方法

查询类型并允许您从该信息构造的语言没有提供任何内容,但是您可以通过各种方式为您的类层次结构提供功能,其中最简单的是使用虚拟方法:

 struct Base {
  virtual ~Base();
  virtual std::auto_ptr<Base> clone(/*desired parameters, if any*/) const = 0;
};

这做了一些稍微不同的事情:克隆当前对象。这通常是您想要的,并允许您将对象作为模板保留,然后您可以根据需要对其进行克隆和修改。

Tronic 上扩展,您甚至可以 生成 克隆功能

为什么是 _autoptr ?因此,您可以使用 new 来分配对象,使所有权的转移显式化,并且调用者毫无疑问 delete 必须释放它。例如:

 Base& obj = *ptr_to_some_derived;
{ // since you can get a raw pointer, you have not committed to anything
  // except that you might have to type ".release()"
  Base* must_free_me = obj.clone().release();
  delete must_free_me;
}
{ // smart pointer types can automatically work with auto_ptr
  // (of course not all do, you can still use release() for them)
  boost::shared_ptr<Base> p1 (obj.clone());
  auto_ptr<Base>          p2 (obj.clone());
  other_smart_ptr<Base>   p3 (obj.clone().release());
}
{ // automatically clean up temporary clones
  // not needed often, but impossible without returning a smart pointer
  obj.clone()->do_something();
}

对象工厂

如果您希望完全按照您的要求进行操作并获得一个可以独立于实例使用的工厂:

 struct Factory {}; // give this type an ability to make your objects

struct Base {
  virtual ~Base();
  virtual Factory get_factory() const = 0; // implement in each derived class
    // to return a factory that can make the derived class
    // you may want to use a return type of std::auto_ptr<Factory> too, and
    // then use Factory as a base class
};

许多相同的逻辑和功能都可以用于克隆方法,因为 _getfactory 完成了一半的相同角色,而返回类型(及其含义)是唯一的区别。

我也已经报道过 几次 工厂了 您可以调整我的 SimpleFactory 类,以便您的工厂对象(由 _getfactory 返回)持有对全局工厂的引用以及传递给创建的参数(例如类的注册名称 - 考虑如何应用 boost::functionboost::bind 使其易于使用)。

原文由 Roger Pate 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题