C++ How to block negative numbers being passed as argument where unsigned is expected

老子叫甜甜 提交于 2019-12-06 12:16:16

I created a small function template that checks whether the input lies within the range of the output data type, and throws an exception otherwise. It requires that the input and output data types are integral, and that the size of the input data type is larger than the output data type.

template<typename DestType, typename SrcType>
DestType range_check_and_convert(SrcType const& src)
{
    static_assert(sizeof(SrcType) > sizeof(DestType), 
        "SrcType must be larger than DestType");
    static_assert(std::is_integral<SrcType>::value &&
                  std::is_integral<DestType>::value, "integral types only");

    if(src > static_cast<SrcType>(std::numeric_limits<DestType>::max())) {
        throw std::out_of_range("input too big");
    } else if(src < static_cast<SrcType>(std::numeric_limits<DestType>::min())) {
        throw std::out_of_range("input too small");
    }

    return static_cast<DestType>(src);
}

Live demo

typ1232

By declaring the contructor to only take unsigned values you basically already "block" that negative numbers can be passed as parameters.

You can still write that you pass -1 to the function, but what the function then sees is the unsigned interpretation of that negative number, see this question.

For example in a 32-bit windows application passing -1 would result in an Id of 0xffffffff or 4294967295. Now you have to decide, whether this is a valid input for your application, but it probably is, because it's still a positive number. On the other hand an age of -1 is probably an invalid input, because it is unlikely to be 4294967295 years old. As you noticed, you can't check your unsigned value for -1. You have to check if age is bigger than for example 200, because -1 is effectively a large number when given as an unsigned parameter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!