What's a better way to detect negative numbers without using a literal?
Normally to detect a negative number, you just do if(x < 0) ...
. But what's the best way to do this without the hard-coded literal? It's not the value that I need to avoid, it's the datatype. I am looking for something in the style of <algor开发者_如何学运维ithm>
.
I have the following solution, but is there a better way? Something tells me this is not as efficient as possible.
template<typename T>
inline bool is_negative(const T& n)
{
return n < (n - n);
}
I want to use the same restrictions that uses. So it's fine to require that T
implement arithmetic operators, but nothing more specific / specialized than that.
Otherwise we could solve this by just requiring that T
implement:
bool operator <(int)
T()
(default constructor which we assume equals 0)- Or why not just require
bool IsNegative()
It's just for my own curiosity; not for use in any project.
return n < T();
(Now I wonder why you have that restriction).
What's wrong with if (x < T(0))
?
Since you are seemingly interested in numeric types, a very natural requirement for such types is that they provide a constructor which takes a fundamental type (int, or double).
I find it more natural that default construction, which may not exist, or have different semantics (undefined, not-a-number, etc. An example is the time classes from eg. boost::posix_time
which default construct to invalid dates)
Checking if something is less than literal zero is right solution. It's the most clear about your intent. It's also the most efficient, but please stop thinking about efficiency when you are checking if a number is negative. That's a bad thing.
精彩评论