【问题标题】:Get the type of the class in a static function c++在静态函数c ++中获取类的类型
【发布时间】:2016-06-19 09:20:50
【问题描述】:

我有这段代码:

struct Type{
  const char* name;
  // other stuff
};

template <class T>
class Base{
 public:
    // some other functions
    static const Type *Get_Type(){
       /* Get the STATIC type of the class and make a new Type object */
    virtual const Type *My_Type();
};

编辑:

我想实现两个成员函数,Get_Type() 和 My_Type()。 从 Base 继承的每个派生类都像这样继承 Base

我无权访问任何派生类,也无法更改 Get_Type() 和 My_Type() 的声明,但其他一切都是允许的。

Get_Type() - 应该实现返回调用它的类的类型。

My_Type - 应该实现返回调用对象的动态类类型。

例如:

class Derived1: public Base<Derived1> {
 public:
    Derived1() {}
};

class Derived2 : public Derived1 , public Base<Derived2> {
 public:
    Derived2() {}
};

int main() {
    Derived1* b= new Derived2();
    Derived2::Get_Type(); // should return a struct Type with name=Derived2
    b->My_Type(); // should return a struct Type with name=Derived2
    return 0;
}

我的问题是:

1) 我如何知道调用类的类型,在静态函数 Get_Type 的主体内?

2) 如何在 My_Type() 的主体中获取对象 (this) 的动态类型?

【问题讨论】:

  • 你不能用静态函数做到这一点。
  • 有办法解决吗?我可以更改 Base 但不能更改任何派生类
  • 你可以使用基类中的普通成员函数和typeid(this)来捕捉实际的类名。
  • 你的意思是非静态成员函数?我以为我不能从静态调用非静态
  • 为什么需要静态函数?我不明白你的意思。

标签: c++ oop inheritance static-members


【解决方案1】:

C++ 中没有虚拟静态。你能得到的最接近的是:

  • 使其成为虚拟成员函数
  • 有一个继承自 Base 的中间 BaseGetTypeImpl 模板类
  • 让 BaseGetTypeImpl 使用 T 的类型实现 Get_Type()
  • 声明派生时,从 BaseGetTypeImpl 继承

这称为 CRTP。

对此的替代方案 - 因为您只需要类型 - 将是在基础(即全局)外部声明的特征模板类。

【讨论】:

  • 派生类直接从 Base 继承,我不能创建中间类(也不能更改函数的声明)所以我想第一个解决方案对我不起作用。但是,如何使用特征模板类?
  • 第一件事。我现在不清楚您是否将BaseBase&lt;Derived&gt; 作为您的基类...
  • 如果它是 Base,您可以将 My_Type() 设为非虚拟静态并在 Base 中说 Derived::My_Type()。
  • 那么为什么是虚拟的?为什么不只是static const Type *Get_Type(){ return Derived::Get_Type(); };
  • Get_Type 不是虚拟的,它是静态的 const Type *Get_Type。至于 static const Type *Get_Type(){ return Derived::Get_Type(); };如果派生类不重载函数,它不会工作吗?
【解决方案2】:

答案是从模板参数中获取类型。 Get_Type() 的完整定义是:

template<class T>
const Type *Base<T>::Get_Type() {/* get T's name and construct a Type struct */}

从 T 你可以得到调用类的类型。

对于 My_Type(),定义为:

virtual const Type *My_Type(){
   return this->Get_Type();
}

由于 c++ 使用动态绑定,被调用的成员函数将是调用对象的动态类之一。

【讨论】:

    猜你喜欢
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2012-10-18
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多