c++c++14type-traitsnumeric-limits

Smallest expressible value above given value


Given a variable defined as

T x;

where T is a generic arithmetic type (i.e. such that std::is_arithmetic<T>::value), is there a simple expression (e.g something from std::numeric_limits) that evaluates to the lowest value y expressible in T such that y > x?

(i.e. a kind of generalized increment..)


Solution

  • You can use std::nextafter.

    Note that here I use std::numeric_limits<Floating>::max(), if you want meaningful behavior for infinities, you might want to modify the code.

    #include <iostream>
    #include <limits>
    #include <cmath>
    #include <type_traits>
    #include <iomanip>
    
    template <typename Floating,
        std::enable_if_t<std::is_arithmetic_v<Floating> && !std::is_integral_v<Floating>, bool> = false>
    Floating generic_next_val(Floating val) {
        return std::nextafter(val, std::numeric_limits<Floating>::max());
    }
    
    template <typename Integral,
        std::enable_if_t<std::is_arithmetic_v<Integral> && std::is_integral_v<Integral>, int> = 0>
    Integral generic_next_val(Integral val) {
        return static_cast<Integral>(val + static_cast<Integral>(1));
    }
    
    int main() {
        int a = 1;
        float f = 0.0f;
        std::cout << std::setprecision(20) << generic_next_val(f) << " " << generic_next_val(a) << std::endl;
        return 0;
    }