elegant way to get a variables limit Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of elegant way to get a variables limit without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

Answer

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.

We are here to answer your question about elegant way to get a variables limit - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji