
On 12/23/09 10:37, Stefan Strasser wrote:
Am Wednesday 23 December 2009 01:40:39 schrieb Slawomir Lisznianski:
template <typename T> struct envelope { size_t len = sizeof(T); // <--- compiler may pad here, hence this doesn't work... T body; };
So, given an arbitrary type T, we want to create an envelope that will have the size of T immediately before it, with no padding between len and body.
The user would then be able to:
envelope<MyStruct> env;
env.body.x = ...
send(env);
you can't make the compiler skip alignment, so if you want to keep the user interface, you have to redirect the accesses to a char array. something like this:
template
struct envelope_base{ char data[HeaderSize + sizeof(T)]; }; template<class T> struct envelope : envelope_base
{ envelope() : len(*reinterpret_cast (data)) , body(*reniterpret_cast (data+sizeof(size_t)){ len=sizeof(T); } size_t &len; T &body; }; template
void send(envelope_base const &); I'm curious if anyone has run into something similar and have a clean solution. Our code currently has to defer to temporary buffers and memcpy'ing data back to it.
not sure how "clean" that solution is. it might technically even be undefined behaviour. There's the composite_tagged_seq
in the composite_tagged_seq.zip file here:
http://www.boostpro.com/vault/index.php?&directory=Data%20Structures However, it essentially does the memcpy'ing the data which you dislike; however, as Stefan points out, you've got to do that if you plan on actually using the data as intended (i.e. properly aligned). However, the composite_tagged_seq template makes the packing and unpacking pretty easy (I think). I've an updated version of the code if you're interested. -Larry