Changing type without changing bits

后端 未结 2 1691
闹比i
闹比i 2020-12-12 03:03

I want to take a stack variable and reinterpret cast it into an unsigned integer type of the same size in bytes. For example, I might want to take double<

2条回答
  •  情书的邮戳
    2020-12-12 03:39

    If you don't want to have undefined behavior due to violating the aliasing restrictions (C++11 3.10/10) then you need to access the object representations as characters:

    template 
    int_type caster(const T& value) {
        int_type v;
        static_assert(sizeof(value) == sizeof(v), "");
        std::copy_n(reinterpret_cast(&value),
                    sizeof(T),
                    reinterpret_cast(&v));
        return v;
    }
    

    High quality compilers will optimize the copy away. E.g., this program:

    int main() {
        return caster(3.14f);
    }
    

    effectively optimizes to return 1078523331; on Intel processors.

提交回复
热议问题