Reputation: 73366
I want to use something for positive infinity. However, the data type my code uses is typedef'ed by other people's class. That means that it can an int, a float, a double and pretty much numerical types.
Previously when I used infinity, I would something like INT_MAX
for integers and so on. However, can I determine (at compile) the type I am using?
I found this answer, but I don't think it's what I am looking for.
But on the other hand I can't think of an elegant method to achieve this.
In code:
typedef float FT;
// in another file
//if FT is int
int inf = INT_MAX;
...
//if FT is float
float inf = FLOAT_MAX;
But still, this would not be nice, because then I want to pass it as a parameter to a function. What would be the signature of the function is the first problem that comes to mind.
[EDIT]
The signature could use the typedef.
Upvotes: 1
Views: 909
Reputation: 1824
Use std::numeric_limits
.
#include <limits>
#include <type_traits>
template <typename T, typename enable_if_helper = void>
struct get_infinity_helper;
template <typename T>
struct get_infinity_helper<T, typename std::enable_if<std::numeric_limits<T>::has_infinity>::type>
{
static constexpr T infinity = std::numeric_limits<T>::infinity();
};
template <typename T>
struct get_infinity_helper<T, typename std::enable_if<!std::numeric_limits<T>::has_infinity>::type>
{
static constexpr T infinity = std::numeric_limits<T>::max();
};
Then use get_infinity_helper<T>::infinity
.
Upvotes: 2
Reputation: 1987
Maybe you could check out numeric_limits<T>
.
// numeric_limits example
#include <iostream> // std::cout
#include <limits> // std::numeric_limits
typedef float FT;
int main () {
std::cout << std::boolalpha;
std::cout << "Minimum value for FT: " << std::numeric_limits<FT>::min() << '\n';
std::cout << "Maximum value for FT: " << std::numeric_limits<FT>::max() << '\n';
std::cout << "FT is signed: " << std::numeric_limits<FT>::is_signed << '\n';
std::cout << "Non-sign bits in FT: " << std::numeric_limits<FT>::digits << '\n';
std::cout << "FT has infinity: " << std::numeric_limits<FT>::has_infinity << '\n';
return 0;
}
With typedef float FT;
Minimum value for FT: 1.17549e-38
Maximum value for FT: 3.40282e+38
FT is signed: true
Non-sign bits in FT: 24
FT has infinity: true
With typedef int FT;
Minimum value for FT: -2147483648
Maximum value for FT: 2147483647
FT is signed: true
Non-sign bits in FT: 31
FT has infinity: false
Upvotes: 5
Reputation: 25409
You can query the type at run-time using the typeid
operator. However, this won't solve your problem. If all you want is the most positive number a type can hold, use std::numeric_limits<FT>::max()
. Note that there is also std::numeric_limits<FT>::has_quiet_NaN()
. These are compile-time constexpr
essions, which is what makes them really useful.
Upvotes: 3