sizeof() not working ?!?

Started by
19 comments, last by Trienco 11 years, 2 months ago

Last time I needed to serialize data to send and receive messages, I ended up building a stream like container and forwarding one operator (&, as inspired by boost) to either << or >> depending on stream type. So each message had one function that would stuff all members into the container or get it out. A few overloads for C-strings, arrays, etc., however no handling of endianness (at least it was never used, there was a very inefficient template to reverse byte order).

It wasn't bullet proof and because of all the templates the user could still put in entire structs (so it was his job to worry about padding). The core of each "stream" was essentially something like

template <typename T>
OutStream& operator<<(const T& data)
{
    buffer.resize( buffer.size() + sizeof(T) );
    memcpy(buffer + pos, &data, sizeof(T));
    pos += sizeof(T);
}
 
//some overloads of <<
 
//same for InStream and >>
 
template<typename T>
inline InStream& operator&(InStream& stream, T& data) { return stream >> data; }
 
 
template<typename T>
inline OutStream& operator&(OutStream& stream, T& data) { return stream << data; }

For each message there was a function like

template<class StreamType>
bool packUnpack(StreamType& stream)
{
     stream & member1 & member2 & member3 & member4;
     return !stream.fail();
}

Adding a member still required to change that function, but reading/writing was consistent, sizes were determined automatically (so using types with fixed size is important) and it worked well enough for what it was used for.

f@dzhttp://festini.device-zero.de

This topic is closed to new replies.

Advertisement