Boost logo

Boost :

Subject: Re: [boost] Proposed templated integer_sort
From: Scott McMurray ([hidden])
Date: 2008-12-16 10:34:39

On Tue, Dec 16, 2008 at 10:19, Giovanni Piero Deretta
<gpderetta_at_[hidden]> wrote:
> On Tue, Dec 16, 2008 at 3:03 PM, Pyry Jahkola <pyry.jahkola_at_[hidden]> wrote:
>> suggest using a union instead, for the purpose of treating a float as
>> integer:
>> template <typename To, typename From>
>> inline To bitwise_cast(From const & from) {
>> BOOST_STATIC_ASSERT(sizeof(To) == sizeof(From));
>> union { To to; From from; } u;
>> u.from = from;
>> return;
>> }
> This is also undefined behavior even if it is explicitly supported by
> most compilers as an extension. It is not necessarily better than a
> memcpy and might actually be slower.

Empyrically, putting the following into the LLVM online demo
( shows that, in llvm-g++ at least, the
(intermediate) code generated from the memcpy is optimal:

#include <string.h>
int foo(float const y) {
    int x;
    return x;

define i32 @_Z3foof(float %y) nounwind readnone {
        %0 = bitcast float %y to i32 ; <i32> [#uses=1]
        ret i32 %0

So since the memcpy is always safe and doesn't break the aliasing
rules, it certainly seems the best approach.

Boost list run by bdawes at, gregod at, cpdaniel at, john at