问题
So from what I know the following two functions' behavior should be exactly the same. However, if I implement using the first one, the compiler seems can't realize it's equivalent to the second. Is there anyway to hint the compiler to use the second ?
In another words, I hate to do the static_cast things... Anyway to avoid it?
// In my real use case, range will never be negative....
// All I want is to return (diff > range || diff < 0) assuming range >=0
bool IsOutofRange1(int diff, int range) {
if ((range >= 0) && (diff > range || diff < 0)) return true;
if (range < 0 && diff > range && diff < 0) return true;
return false;
}
bool IsOutofRange2(int diff, int range) {
if (static_cast<unsigned>(diff) > static_cast<unsigned>(range)) return true;
return false;
}
回答1:
If your range in never negative, why do you use a signed type for it (yeah, I know you hate casting) ? How about overloading:
bool IsOutofRange(int diff, int range)
{
....
}
bool IsOutofRange(int diff, unsigned range)
{
if (static_cast<unsigned>(diff) > range) return true;
return false;
}
Of course to force compiler to use the second version you would (oh my God...):
IsOutofRange(diff,static_cast<unsigned>(range));
I hope that helps, and I am deeply sorry about the static_cast'ing.
来源:https://stackoverflow.com/questions/31352357/how-to-make-the-c-compiler-to-use-the-unsigned-to-signed-trick-for-optimizatio