gen*_*gen 2 c++ math overloading
我需要使用cmath的abs()函数,但Visual Studio说它已经重载了,我甚至无法使用这样的东西:
unsigned a = 5, b = 10, c;
c = abs(a-b);
Run Code Online (Sandbox Code Playgroud)
我不知道如何正确使用它.
版本中<cmath>的版本适用于浮点类型,因此没有明确的最佳匹配.整数类型的重载在<cstdlib>,所以其中一个将产生良好的匹配.如果您使用的abs是不同类型,则可以同时使用包含和重载解析来完成其工作.
#include <cmath>
#include <cstdlib>
#include <iostream>
int main()
{
unsigned int a = 5, b = 10, c;
c = std::abs(a-b);
std::cout << c << "\n"; // Ooops! Probably not what we expected.
}
Run Code Online (Sandbox Code Playgroud)
另一方面,这不会产生正确的代码,因为表达式a-b不会调用整数提升,因此结果是a unsigned int.真正的解决方案是使用带符号的整数类型来表示差异,以及整数类型的std::abs重载.