Question

I have some classes corresponding to some datatypes which are supposed to encode and decode the actual data. eg, class MyInt32 will have function for encoding an integer value and decoding it from a stream of encoded bytes. All these classes are derived from a base class, MyTypes. While decoding, after getting the value from the encoded string I put the value in the corresponding datatypes, eg int in case of MyInt, and return the data as a void *.

At the receiving side, I typecast the pointer to (int *) and then dereference it to put it into the result.

But now I need a type for having arrays as well. In case of arrays I am using templates to say what the array is going to hold. that is,

template<typename T>
class MyArray:public MyType
{
    vector<T *> mydata;
    ....
};

In the decode function I will call the decode of the type T. But now it just returns a void*. My array won't be knowing what the decoded type will be. So I can't typecast the void * and dereference it to get the value. That is, If I take an array of MyInt

MyArray<MyInt> data;

The array 'data' won't know that its decoded result will be a vector<int>. And it is preferable to pass the data as vector<int> rather than vector<int*> How can I achieve it?

Was it helpful?

Solution

Make sure each type that can be used as the template argument (MyInt etc.) has a typedef with a given name, such as RepresentedType:

class MyInt : public MyType {
public:
    typedef int RepresentedType;
    ....
};

Now you can use it in the templated class:

template<typename T>
class MyArray : public MyType {
    ....
    T::RepresentedType * something();
};

(I hope this is what you wanted.)

OTHER TIPS

you can use boost::any class for your purpose. It's the easy and efficient way to get the value of any stored data based on Runtime type Identification.

vector<boost::any> somevec;
boost::any obj= new MyClass<SomeTemplate>;
somevec.push_back(obj);

SomeTemplate ret = boost::any_cast<SomeTemplate>(somevec[0]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top