|
Boost : |
From: Pavol Droba (droba_at_[hidden])
Date: 2002-11-24 10:03:41
On Sun, Nov 24, 2002 at 01:26:05PM +0100, Terje Sletteb? wrote:
> >From: "Pavol Droba" <droba_at_[hidden]>
>
> > I have developed a simple cast function which I found very useful. Here it
> is:
> >
> > template< typename T >
> > inline T offset_cast( void* p, unsigned int offset=0 )
> > {
> > return reinterpret_cast< T >( static_cast<unsigned char*>( p )+offset );
> > }
> >
> > template< typename T >
> > inline T offset_cast( const void* p, unsigned int offset=0 )
> > {
> > return reinterpret_cast< T >( static_cast<const unsigned char*>(
> p )+offset );
> > }
> >
> > Its purposes is to simplify a mapping of C-like structure onto binary
> data. Here is
> > the example: Assume thath you have a network packet in raw format, and you
> want
> > to read IP-header information. You could do following:
> >
> > ip_header* ip=offset_cast<ip_header>( packet, ip_header_offset );
> >
> > instead of ugly pointer arithmetic.
>
> Uhm, I think pointer arithmetic could be preferrable to casts, particularly
> reinterpret_cast, as pointer arithmetic is at least not
> implementation-dependent, unlike the reinterpret_cast.
I don't see you point here. I'm not sure why whould be reinterpret_cast
implemetation dependent and pointer aritmetic not?
>
> Also, I find nothing ugly about pointer arithmetic - in fact, STL is based
> on it, except that it's abstracted as "iterators". int array[10];
> std::for_each(array,array+10,f) is pointer arithmetic. Do you find that
> ugly, as well?
I'm sorry, you are right, ugly is not a good term here. However the purpose
of the offset cast is not to avoid pointer arithemtic at all cost.
Ist purpose is to simplify mapping of structures over memory buffers.
Problem here is to shift a pointer n-bytes forward. You can do it
with pointer arithmetic, but still you have to cast the pointer to something
what have size of 1 otherwise you will not shift it n-bytes but n*sizeof(type).
So offset_cast handles this for you. It is merely a shorcut, which could be
very handy if you are working with raw data.
Regards,
Pavol
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk