开发者

vector of type/class for typecasting null pointer

开发者 https://www.devze.com 2023-04-06 04:54 出处:网络
I have program that currently use typecast for a null-pointer vector开发者_JS百科 according to the following:

I have program that currently use typecast for a null-pointer vector开发者_JS百科 according to the following:

(Note the code is "principal", I have stripped most unecessary content.

for (i=0;i<NObjects;i++)
{
    switch (ObjectTypes[i])
    {
    case 1:
        ((File_GUI*) (NullVector[i]))->function();
        break;

    case 2:
        ((Point_GUI*) (NullVector[i]))->function();
        break;

    case 3....etc
    }
}

Is there any way to replace to large amount of case 1, case 2 etc with a simple array that is used for the typecasting? Hence the code would look something like this (Where of course the TypeCastVector must be created earlier and containt the datatypes for each index i:

for (i=0;i<NObjects;i++)
{
    ((typeCastVector[i]*) (NullVector[i]))->function();
 }

If possible, this would save me tons of lines of codes.


I agree with Kerrek SB, a redesign is probably wanted so as to use a virtual function call and a base class for this purpose. If for some reason you really don't want to give File_GUI, Point_GUI, etc a base class you could do this...

struct BaseStorer
{
    virtual void CallFunction() = 0;
};

template<typename T>
struct TypeStorer : public BaseStorer
{
    TypeStorer(T* _obj) : obj(_obj) {}
    virtual void CallFunction() { obj->function(); }

    T* obj;
};

Store an array of BaseStorer* which are new TypeStorer<File_GUI>(new File_GUI(...)). Your loop would look like...

for (i=0;i<NObjects;i++)
{
    baseStorerVector[i]->CallFunction();
}


I am having the same opinion as mentioned in comments. Presently your ObjectTypes[] seems to be an array (or vector of ints). You may want to change it to an array of pointers (handles) of a common base class. For example,

GUI *ObjectTypes[NObjects];

Where class hierarchy is like,

class GUI {  // abstract base class
public:
  virtual void function () = 0; // make it an abstract method
};

class File_GUI : public GUI {
  void function () { ... }
};
...

Now you can replace your call in a single line as,

for (i=0;i<NObjects;i++)
{
    ObjectTypes[i]->function();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消