Template version of std::abs

柔情痞子 提交于 2019-12-08 14:29:53

问题


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

回答1:


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.




回答2:


This suffers the usual problem of matching everything.

An example of a type for which abs makes sense but this implementation does not is complex<double>.




回答3:


Because type 'T' can access any data type including char. So what are you expecting if someone will pass a char to the abs function. :)



来源:https://stackoverflow.com/questions/29411486/template-version-of-stdabs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!