Polymorph collection in C++
I need to code a class that recieves a collection with any number of elements of any 'primitive' type. I also need to be able to know the type of each member (or at least the size of the type). The purpose of this class is to serialize the elements to store them in a file in fixed length registers.
Is this posible?
I know that C++ is statically typed and that there's no common parent regarding inheritance (such as Object in Java). So, I cannot recieve an array or a vector, as all the elements should have the same type.
I also thought of an array of pointers, but in such way I wouldn't know the elements type or its size.
Any ideas?
PS: couldn't find similar question, but if 开发者_JAVA百科it exists, please redirectme.
Have you looked into boost::any ? It sounds like it might be a good match for your problem: storing a polymorphic collection of objects, without the loss of type information that occurs with arrays of void *
or similar hacks.
You can do it with a template class (or template function):
template<class T>
class MyClassT
{
void receive(const T* array, size_t n)
{
size_t sizeOfT = sizeof(T);
... code here to serialize the array ...
}
};
If you meant the more complicated question which Shhnap explained in a comment, then maybe something like this:
class ISerializable
{
public:
size_t getSize() const = 0;
const void* getBytes() const = 0;
};
template<class T>
class SerializableT : public ISerializable
{
public:
size_t getSize() const { return sizeof(T); }
const void* getBytes() const = { return &m_data; }
SerializableT(T data) : m_data(data) {}
private:
T m_data;
};
typedef vector< smartptr<ISerializable> > Serializable;
void serialize(const Serializable& serializable)
{
for(Serializable::const_iterator it = serializable.begin(), end = serializable.end(); it != end; ++it)
{
const smartptr<ISerializable>& element = *it;
size_t size = it->getSize();
const void* bytes = it->getBytes();
save(bytes, size); //to be implemented
}
}
If you're ok with boost, either use Boost.Any like Jim stated, or go all the way and just use their serialization library.
精彩评论