Search code examples
c++c++14

Is there a C++ way to get the min/max value of a scalar?


Our unit tests test min/max values. If the underlying data type of the tested variable changes, then the tests needs to be updated - if we spot it & remember to to do so.

If we talk only of unit8_t, 16, 32, 64, is there any way to say in the unit test "min/max value of the variable" - as long as it is one of those types?

E.g. if unit8_t height becomes unit16_t height, I don't want to have to update the min/max unit test.

I am happy if I can do that for those simple tests. Anything else is a bonus.


Solution

  • You can use numeric_limits to get the the minimum and maximum value for the type:

    #include <limits>
    
    template<class T>
    bool has_min_value(T val) {
        return val == std::numeric_limits<T>::lowest();
    }
    
    template<class T>
    bool has_max_value(T val) {
        return val == std::numeric_limits<T>::max();
    }
    

    Demo

    lowest() and min() return the same thing for integral types.

    For floating-point types, lowest() typically returns -max() and min() returns:

    • The minimum finite value.
    • For types with subnormal numbers, returns the minimum positive normalized value.