Boost logo

Boost :

From: Marcus Lindblom (macke_at_[hidden])
Date: 2006-09-22 15:42:03


Martin Bonner wrote:
> ----Original Message----
> From: Sohail Somani
>
>> Marcus Lindblom wrote:
>>> Olivier Grant wrote:
>>>> I agree on your point, on the other hand, you can do this :
>>>>
>>>> class vector3d
>>>> {
>>>> public:
>>>> float x, y, z;
>>>>
>>>> float operator[]( int index ) const
>>>> { return ((float *)this)[index]; }
>>>>
>>>> float & operator[]( int index )
>>>> { return ((float *)this)[index]; }
>>>>
>>>> /* ... */
>>>> };
>>>>
>>>> in which case "v.x" and "v[0]" are the same thing. this is what I
>>>> currently have. Now some people will argument its a hack maybe.
>>>>
>>> I've sometimes done just:
>>>
>>> class vector3d
>>> {
>>> public:
>>> float x, y, z;
>>>
>>> float operator[]( int index ) const
>>> { return (&x)[index]; }
>>>
>>> /* ... */
>>> };
>> Won't that not work in the presence of padding?
> In theory, yes. In practice, I can't see why any compiler would bother
> adding such padding.
>
> A more serious problem is if you start mixing usages. A compiler is
> quite likely to assume that assignments through the result of the index
> operator don't affect .y or .z, and optimize on that basis.

Why should it? The offset to memory will be the same, so it should treat
it as access to the same memory location, if it optimizes well in the
backend ('assembly' AST).

Cheers,
/Marcus


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