|
Boost : |
From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2002-11-24 07:26:05
>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.
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?
"Ugly" is typically more used for casts. Whether they are wrapped in a
function, like the above, or not. This because they circumvent the type
system. This is something pointer arithmetic doesn't do.
Regards,
Terje
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk