std :: abs的模板版本 [英] Template version of std::abs

查看:420
本文介绍了std :: abs的模板版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处列出了当前的重载 std :: abs 在C ++中。我想知道为什么不只是定义下面的模板,让所有的丑陋的C风格的重载?

Here lists the current overloads of std::abs in C++. I'm wondering why not just define the following template and let go all the ugly C-style overloads?

template <typename T> inline
T abs(const T& v) { return v < 0 ? -v : v; }


推荐答案

请参阅 LWG问题2192 。目前, std :: abs(x-y)如果 x y 未签署,则这会捕获一个微妙的编程错误。随着建议的改变,它编译,但完全错了。 abs(3u-4u)将大于2,实际上它 UINT_MAX

See LWG issue 2192. Currently, std::abs(x-y) < 2 fails if x and y are unsigned. This catches a subtle programming error. With the proposed change, it compiles but does entirely the wrong this. abs(3u-4u) would be much larger than 2, in fact it's UINT_MAX.

这篇关于std :: abs的模板版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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