Reputation: 6883
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.
Upvotes: 3
Views: 2681
Reputation: 69902
And just for completeness, skirting on the edge of legality:
#include <iostream>
#include <limits>
template<class T>
T biggest(T&)
{
return std::numeric_limits<T>::max();
}
int main()
{
std::int64_t i = biggest(i);
std::cout << i << std::endl;
return 0;
}
Upvotes: 3
Reputation: 145359
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.
Upvotes: 1
Reputation: 9416
What about auto?
auto varname = std::numeric_limits<int64_t>::max();
There is only one place mentioning the type.
Upvotes: 1