C ++ dynamic_cast与存储静态枚举中的对象类型? [英] C++ dynamic_cast vs storing object type in a static enum?

查看:154
本文介绍了C ++ dynamic_cast与存储静态枚举中的对象类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在为一个框架开发一个大的层次结构,需要很多类型转换。我的问题是,如何愚蠢的一个想法是放入一个静态成员,该成员使用枚举来存储层次结构中的所有对象类型。使每个类的成员静态不会增加实例化的对象大小,并且将提供一种(可能)更快的方式来确定运行时期间对象的类型比dynamic_cast。



至少这是基本的想法。

解决方案

我不知道你是怎么决定的从对象之间共享的静态变量确定每个对象的类型。除非你有一些虚函数,你为每个类重写,但然后你不需要静态变量,只需这样做:

  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


I am developing a big hierarchy of classes for a framework that will require quite a lot of type casting when it gets done.

My question is, how stupid of an idea is to put in a static member that uses an enum to store all the object types in the hierarchy. Having the member static for every class will not increase the instanced object sizes, and will give a (potentially) faster way to determined the type of an object during runtime than dynamic_cast.

At least that's the basic idea. How adequate would this approach be, and are there any potential flaws?

解决方案

I don't know how you were gonna determine the type of each object from a static variable that is shared between the objects. Unless you have some virtual function that you override for each class, but then you don't need the static variable at all, just do something like this:

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

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

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

Not the fastest solution, but several magnitudes faster than dynamic_cast or typeid.

这篇关于C ++ dynamic_cast与存储静态枚举中的对象类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆