检测我们是否在 child class 或基地 class

Detecting if we are in child class or base class

我有问题,我尝试使用RTTI来解决。

我有一个classBase和childrenclasses(在例子中,我只显示一个Child

class Base {
    virtual void Eval() {

      // normal treatment
              +
      // treatment only for Base instance
    }
};

class Child : Base {
    void Eval() {
      // call Base Eval
      Base::Eval();
      //other treatment
    }
};

问题是,在 Base::Eval 中,有些处理在我从 Child 调用时不想执行。 我的意思是,在 Child::Eval 中,当我们调用 Base::Eval 时,我们只需要执行的正常处理。

为此,我想到了RTTI。我不知道这是否是最好的使用方式,我想做这样的事情:

class Base {
        virtual void Eval() {

          // normal treatment
                  +
          if (typeid(this).name() == typeid(Base).name()) {         
            // treatment only for Base instance
          }
        }
    }

问题是:是否允许这样做? 我必须检查 typeid.name() 吗? 或者 typeid() 就足够了吗?

诸如此类的情况几乎总是表明设计不当。基础 class 不应该知道其派生的 classes.

如果您想为派生 classes 提供自定义部分基本行为的选项,请使用虚函数和 "template method" 设计模式:

class Base
{
public:
  virtual void Eval() {
    // normal treatment
    Eval_CustomisationHook();
  }

protected:
  virtual void Eval_CustomisationHook()
  {
    // Do the stuff
  }
};

class Child : public Base
{
protected:
  virtual void Eval_CustomisationHook()
  {} // do nothing
};

或者,您可以只委托查询:

class Base
{
public:
  virtual void Eval() {
    // normal treatment
    if (doOptionalEvalPart()) {
      // do it here
    }
  }

protected:
  virtual bool doOptionalEvalPart()
  {
    return true;
  }
};

class Child : public Base
{
protected:
  virtual bool doOptionalEvalPart()
  {
    return false;
  }
};

同时回答您原来的问题:正确的形式是比较 std::type_info 对象,而不是它们的名称。并且不要忘记您必须取消引用 this。所以代码看起来像这样:

if (typeid(*this) == typeid(Base))

这会做你想做的事。但正如我上面所说,这很可能不是正确的方法。