开发者

How to provide a single function to get data of any derived object through base class pointer?

i have code like below. Base is the base class and D1, D2, D3 are derived classes. D1, D2 and D3 class objects can hold int, float and double values respectively. I have a vector of base class pointers. Each one of them can point to any of the derived class objects. Through Base class pointer i should be able to get the data present in any of the derived class.

enum Type
{
   INT,
   FLOAT,
   DOUBLE
};
struct Data
{
   Type type;
   union
   {
       int iVal;
       float fVal;
       double dVal;
   };
};
class Base
{
public:
   virtual Data getData() = 0;
};
class D1: public Base
{
   int i;
public:
   virtual Data getData()
   {
       Data data;
       data.type = INT;
       data.iVal = i;
       return data;
   }
};

class D2: public Base
{
     float f;
public:
    virtual Data getData()
    {
       Data data;
       data.type = FLOAT;
      开发者_如何转开发 data.fVal = f;
       return data;
    }
};

class D3: public Base
{
     double d;
public:
    virtual Data getData()
    {
       Data data;
       data.type = DOUBLE;
       data.dVal = d;
       return data;
    }
};

getData() returns Data object.

Using the type in Data object, i need to extract corresponding value in union.

I am unable to avoid type checking even though i am using virtual function mechanism.

Is there any better way to return data through single interface function ?

EDIT: In my project scenario, at runtime it can generate few D1 objects, few D2 objects and so on. I need to pass all these objects to some other module. So i used vector<Base *> to pass on all the objects to the next module. Is there any better way to pass on all the objects ?

EDIT: Any Non-Boost solution exists ?


In general I'd prefer to avoid such design at all. But if you absolutely have to make it this way, the easiest and fastest method, imho, is to use boost::any.

Update: As it was, absolutely correctly, noted boost::variant may be even more convenient and efficient here, since the used types are known (thanks for the remarks).


It looks like you're trying to do something similar to the VARIANT struct. Can you explain a bit more about why you are attempting this design?


This might be put a bit hard but: object orientation and polymorphism is about letting objects do something, it is not about querying data from objects.
If this is about printing,sending,storing,... data, you could derive from data and let the derived data objects do the printing,sending,storing,..., but in this case, you don't need the data classes: the owning classes can do this too.


Instead of passing one vector of variant objects, what about passing three vectors, each with just one type in it?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜