如何使C ++编译器使用无符号到有符号的技巧优化比较 [英] How to make the C++ compiler to use the unsigned to signed trick for optimization of comparison

查看:219
本文介绍了如何使C ++编译器使用无符号到有符号的技巧优化比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以从我知道以下两个函数的行为应该是完全一样的。
然而,如果我实现使用第一个,编译器似乎不能意识到它相当于第二个。是否还有提示编译器使用第二个?

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 ?

换句话说,我讨厌做static_cast的东西...反正要避免它?

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;
}


推荐答案

,为什么你使用一个签名的类型(是的,我知道你讨厌铸造)?如何重载:

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));

我希望对我有帮助,对static_cast会感到非常抱歉。

I hope that helps, and I am deeply sorry about the static_cast'ing.

这篇关于如何使C ++编译器使用无符号到有符号的技巧优化比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆