|
Boost Users : |
Subject: Re: [Boost-users] alignment question
From: Stefan Strasser (strasser_at_[hidden])
Date: 2009-12-23 11:37:57
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<class T,std::size_t HeaderSize>
struct envelope_base{
char data[HeaderSize + sizeof(T)];
};
template<class T>
struct envelope : envelope_base<T,sizeof(size_t)>{
envelope()
: len(*reinterpret_cast<size_t *>(data))
, body(*reniterpret_cast<T *>(data+sizeof(size_t)){
len=sizeof(T);
}
size_t &len;
T &body;
};
template<class T,size_t HeaderSize>
void send(envelope_base<T,HeaderSize> 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.
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net