在运行时创建相关类型的最佳方法是什么?

时间:2011-11-18 15:52:23

标签: c++ types runtime

如何在运行时确定与另一个类相关的类的类型?

我找到了一个解决方案,唯一的问题是我最终不得不使用必须在所有派生类中使用的定义。

有没有更简单的方法可以做到这一点,不需要定义或复制粘贴?

注意事项:类和相关类都将始终具有各自的基类,不同的类可以共享相关的类,并且在示例中我希望控件类拥有该视图。

#include <iostream>
#include <string>

class model;

class view {
public:
  view( model *m ) {}
  virtual std::string display() {
    return "view";
  }
};

#define RELATED_CLASS(RELATED)\
typedef RELATED relatedType;\
virtual relatedType*createRelated(){\
return new relatedType(this);}

class model {
public:
  RELATED_CLASS(view)
  model() {}
};

class otherView : public view {
public:
  otherView( model *m ) : view(m) {}
  std::string display() {
    return "otherView";
  }
};

class otherModel : public model {
public:
  RELATED_CLASS(otherView)
  otherModel() {}
};

class control {
public:
  control( model *m ) : m_(m),
      v_( m->createRelated() ) {}
  ~control() { delete v_; }
  std::string display() {
    return v_->display();
  }
  model *m_;
  view  *v_;
};

int main( void ) {
  model m;
  otherModel om;

  model *pm = &om;

  control c1( &m );
  control c2( &om );
  control c3( pm );

  std::cout << c1.display() << std::endl;
  std::cout << c2.display() << std::endl;
  std::cout << c3.display() << std::endl;
}

2 个答案:

答案 0 :(得分:1)

您正在尝试实施自己的自定义RTTI 但是,您可以在内置的C ++ RTTI typeid 运算符中使用。

答案 1 :(得分:0)

您可以使用模板来避免#defines,但是,无论哪种方式,请注意您实际上是在使用otherModel的createRelated方法重载返回类型。

可能有更好的方法来做你想做的事。

#include <iostream>
#include <string>

class model;

class view {
public:
  view( model *m ) {}
  virtual std::string display() {
    return "view";
  }
};

class model {
public:
  virtual view* createRelated() {  return new view (this); }
  model() {}
};


template <class Related>
class relatedModel : public model
{
  public:
    relatedModel() : model() {}
    virtual view* createRelated() { return new Related(this);}
} ;


class otherView : public view {
public:
  otherView( model *m ) : view(m) {}
  std::string display() {
    return "otherView";
  }
};

class control {
public:
  control( model *m ) : m_(m),
      v_( m->createRelated() ) {}
  ~control() { delete v_; }
  std::string display() {
    return v_->display();
  }
  model *m_;
  view  *v_;
};

int main( void ) {
  relatedModel<view> m;
  relatedModel<otherView> om;

  model *pm = &om;

  control c1( &m );
  control c2( &om );
  control c3( pm );

  std::cout << c1.display() << std::endl;
  std::cout << c2.display() << std::endl;
  std::cout << c3.display() << std::endl;
}