SQLite is a relational database and those things cannot store C++ objects directly.
Actually the C++ object model doesn't allow a fully transparent persistence but you can try to get somewhat close using specialized tools or libraries. The important point is however that the objects themselves must be designed to support persistence.
If you don't need transparent persistence but only explicit store/retrieval of objects then you can just pick up a serialization method you like (e.g. using a single string, or using separate fields for the attributes). Each method has pros and cons depending on what you want to do with the database (e.g. what kind of searches or updates you want to do).
Something that is also unfortunate about C++ is that its metaprogramming abilities are very poor (just a little better than C) and for example introspection is impossible.
This means that you will need to write your serialization code for each class that you will need to support or you will need to find/buy an external tool that looking at the class definition .h
will generate the needed code for you. It must be an external tool because serialization is something that is outside the very limited reach of template metaprogramming.
Qt itself already has some specialized serialization machinery QDataStream
so may be you can use that for what you are looking for: for example QRect
is serializable and QList<T>
is serializable if T
is.
Using that would require to serialize to a QByteArray
first and then store the blob inside SQLite. For example after writing
template<typename T>
QByteArray serialize(const T& x)
{
QByteArray ba;
QDataStream s(&ba, QIODevice::WriteOnly);
s << x;
return ba;
}
template<typename T>
T deserialize(QByteArray& ba)
{
QDataStream s(&ba, QIODevice::ReadOnly);
T res; s >> res;
return res;
}
you can serialize an object directly to a QByteArray
with
QByteArray ba = serialize(x);
and you can deserialize it with
X x = deserialize<X>(ba);