2

我正在为一个框架开发一个很大的类层次结构,当它完成时需要大量的类型转换。

我的问题是,放入一个使用枚举来存储层次结构中所有对象类型的静态成员是多么愚蠢的想法。为每个类设置成员 static 不会增加实例化对象的大小,并且会提供一种(可能)比 dynamic_cast 在运行时更快地确定对象类型的方法。

至少这是基本的想法。这种方法有多合适,是否有任何潜在的缺陷?

4

2 回答 2

3

我不知道您将如何从对象之间共享的静态变量中确定每个对象的类型。除非您为每个类都覆盖了一些虚函数,但是您根本不需要静态变量,只需执行以下操作:

struct Base
{
   virtual int type() = 0;
};

struct Derived1 : public Base
{
   virtual int type() { return 1; }
};

struct Derived2 : public Base
{
   virtual int type() { return 2; }
};

不是最快的解决方案,但比dynamic_cast或快几个数量级typeid

于 2012-04-18T19:35:49.263 回答
0

这是一个稍微好一点和不同的答案。我不想更改 Timo 的答案,所以提交了一个新答案。这背后的基本原理是避免幻数。当目标不是修改原始类时,有时需要对对象进行类型转换和摆弄以添加新功能。但这不应该允许某人使用幻数。

enum mytypeid {
    DERIVED1,
    DERIVED2,
};

struct Base
{
   virtual mytypeid type() = 0;
};

struct Derived1 : public Base
{
   static const mytypeid mytype = DERIVED1;

   virtual mytypeid type() { return mytype ; }
};

struct Derived2 : public Base
{
   static const mytypeid mytype = DERIVED2;

   virtual mytypeid type() { return mytype ; }
};

//...

void fn(Base &a) {
     if(a.type() == Derived1::mytype) {
        std::cout<<"1"<<std::endl;
     }
}
于 2017-08-30T22:10:25.257 回答