At work, I did a class with template methods to serialize (into a char array) basic types and some std types, like vector and string.
class MySerializer{
public:
// serialize operator
template<typename T>
friend MySerializer& operator<<( MySerializer&, const T&);
// deserialize operator
template<typename T>
friend MySerializer& operator>>( MySerializer&, T& );
private:
std::vector<unsigned char> v;
};
Then, if you need to serialize custom types, you can add specializations as needed. For basic types, you can just copy them byte to byte into v. Custom types need a few more work. Fore example, let's see how to serialize an std::string.
For this use case, you can look at std::string as a pair of asize_t where is stored the size of the string and a char* that points to string's chars. When you serialize a string, you could put its string::size(), casted for example to an uint32_t or uint64_t, into the serializer and then copy into the serializer string::size() characters starting from string::c_str(). When you will deserialize, first you need to read string's size from the serializer, and then put the proper number of chars into your output string.
You may be interested also in this question of mine.
candc++, IMHO, it'scorc++. Choose yours. :-)reinterpret_castis the wrong tool.std::stringorstd::vectorthis way. Look out for a good serialization library likeboost::serializationor google protobuf.