Boost logo

Boost :

From: Larry Evans (jcampbell3_at_[hidden])
Date: 2002-08-09 16:40:36


David B. Held wrote:
[...]

>
>I notice that you try your hardest to stick to C++-style casts, except in
>the
>peculiar construction:
>
> int(static_cast<_T *>((_U *) 1) - offset(1));
>
>Here you cast the constant value 1 to a U*. Very creative. Then you
>subtract
>one byte? And cast back to a T*? What on earth is this code supposed to
>be doing?!?
>
It's doing what the following static template function does
(assume this is defined within
   struct __ptr_base<_T, __false_type> {...};
):
    /**
      offset_from_subclass<_U>():
        Purpose:
          For a subclass, _U, of _T, calculates the offset of _T part of _U.
        Example:
          given:
            struct _U: R,S,_T{};
            _U* pu = new _U;
            _T* pt = pu;
          returns:
            pt - pu in terms of char.
    */
    template <typename _U>
    static offset offset_from_subclass(void)
    {
      char cu[sizeof(_U)];
      _U* pu = reinterpret_cast<_U*>(cu);
      _T* pt = pu;
      int off = int(reinterpret_cast<char*>(pt)-cu);
      return off;
    }

>Let's look at the one place it is called, and see if we can
>bring
>any sanity to this code.
>
> element_type * get() const
> {
> return m_ptr + s_rectify[get_type_id()];
> }
>
>
The reason this works is that the + operation is defined in offsets.h. This
operation converts everything to char* and then recasts it back to
element_type*.
As explained in the comments above offset_from_subclass, it just returns
the difference in terms of char sizes.

I had a lot of trouble understanding this too.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk