Forbid integer conversion with precision loss

后端 未结 3 780
庸人自扰
庸人自扰 2021-02-15 18:00

How to prevent such code from compiling?

#include 
#include 
#include 
#include 

int main() {
  std::         


        
3条回答
  •  被撕碎了的回忆
    2021-02-15 18:18

    I solve this by templates and specialisation:

     template<
            typename T/*the desired type*/,
            typename Y/*the source type*/
        > T integral_cast(const Y& y)
        {
            static_assert(false, "undefined integral_cast");
        }
    

    which I then specialise at leisure if I want the cast to work:

    // Pass through for uint32_t
        template<>
        inline std::uint32_t integral_cast(const uint32_t& y)
        {
            return y;
        }
    

    and

    // Specialisation to convert std::uint32_t to double
        template<>
        inline double integral_cast(const std::uint32_t& y)
        {
            double ret = static_cast(y); // this never loses precision under IEEE754
            return ret;
        }
    

    At the point of use you write code of the form

    int16_t y = integral_cast(std::numeric_limits::max());
    

提交回复
热议问题