What is different about C++ math.h abs() compared to my abs()

后端 未结 8 678
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 07:44

I am currently writing some glsl like vector math classes in C++, and I just implemented an abs() function like this:

template
static         


        
8条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 08:20

    Since they are the implementation, they are free to make as many assumptions as they want. They know the format of the double and can play tricks with that instead.

    Likely (as in almost not even a question), your double is the binary64 format. This means the sign has it's own bit, and an absolute value is merely clearing that bit. For example, as a specialization, a compiler implementer may do the following:

    template <>
    double abs(const double x)
    {
        // breaks strict aliasing, but compiler writer knows this behavior for the platform
        uint64_t i = reinterpret_cast(x);
        i &= 0x7FFFFFFFFFFFFFFFULL; // clear sign bit
    
        return reinterpret_cast(i);
    }
    

    This removes branching and may run faster.

提交回复
热议问题