Opinions on type-punning in C++?

后端 未结 5 442
野趣味
野趣味 2020-12-02 23:42

I\'m curious about conventions for type-punning pointers/arrays in C++. Here\'s the use case I have at the moment:

Compute a simple 32-bit checksum over a
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 00:20

    I know this thread has been inactive for a while, but thought I'd post a simple generic casting routine for this kind of thing:

    // safely cast between types without breaking strict aliasing rules
    template
    ReturnType Cast( OriginalType Variable )
    {
        union
        {
            OriginalType    In;
            ReturnType      Out;
        };
    
        In = Variable;
        return Out;
    }
    
    // example usage
    int i = 0x3f800000;
    float f = Cast( i );
    

    Hope it helps someone!

提交回复
热议问题