Search code examples
c++coding-stylenumeric-limits

elegant way to get a variables limit


is there an better way to set a variables to one of its limits than

varname = std::numeric_limits<decltype(varname)>::max();

especially when initializing

int64_t varname = std::numeric_limits<decltype(varname)>::max();

I normally do not want to use the type in such expressions since its easy to miss this if type is changed.


Solution

  • Re

    I normally do not want to use the type in such expressions since its easy to miss this if type is changed.

    that's easy:

    auto varname = std::numeric_limits<int64_t>::max();
    

    You can reduce the verbosity of std::numeric_limits in many ways, e.g. by an template alias or by defining a function template.

    template< class Type >
    using Limits_ = std::numeric_limits<Type>;
    
    auto varname = Limits_<int64_t>::max();
    

    or

    template< class Type >
    constexpr auto max_of() -> Type { return std::numeric_limits<Type>::max(); }
    
    auto varname = max_of<int64_t>();
    

    In C++14 and later you can make max_of a template variable, which for some reason that I've never seen explained, some people prefer.