任意算术类型的比较:有人知道实现吗?
在编写几个数学实用程序时,我遇到需要实现可以在任意两种基本算术类型之间进行比较的通用实用程序。当我开始编码时,很明显这个操作并不像看起来那么简单,因为我需要正确处理极端情况,特别是当类型具有不同的精度时,即类型之间转换期间的舍入策略变得很重要。考虑:
float a1 = 4.8f;
int a2 = 4;
assert(a2 != (int) a1); //fails erroneously since we truncated a1
float b1 = 40000000.0f; //can represent only 40000000 and 40000004 accurately
long b2 = 40000002;
assert(b1 != (float) b2); //fails erroneously since we now truncated b2
上述可以使用 c++0x 类型特征来实现,以根据提供给比较函数的模板参数自动选择适当的算法。然而,这是相当复杂的,并且有很多地方可能会出现错误,所以我认为自己发明所有东西并不值得。有谁知道正确实现上述内容的库?
While writing several math utilities I bumped into need to implement generic utility that can perform comparisons between any two fundamental arithmetic types. As I began coding, it became clear that this operation is not as straightforward as it seems, since I need correct handling of corner cases, especially when the types have different precision, i.e. rounding strategy during conversion between types becomes important. Consider:
float a1 = 4.8f;
int a2 = 4;
assert(a2 != (int) a1); //fails erroneously since we truncated a1
float b1 = 40000000.0f; //can represent only 40000000 and 40000004 accurately
long b2 = 40000002;
assert(b1 != (float) b2); //fails erroneously since we now truncated b2
The above can be implemented using c++0x type traits to automatically select the appropriate algorithm according to the template arguments supplied to the comparison function. However, this is quite complex and there's quite a lot of places where bugs can creep, so I don't think inventing everything myself is worthwhile. Does anyone know a library that implements the above correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要查看 GNU 的 MP Bignum 库,网址为 http://gmplib.org/。从他们的页面:
You may want to look into GNU's MP Bignum library at http://gmplib.org/. From their page: