我想要理解以下代码的行为,从C++标准角度来看(GCC 9.3,C++20):(代码链接)
#include <cstdlib>
template<class> struct type_tester;
int main() {
type_tester<decltype(abs(0.1))>{}; // int abs(int) overload is selected for some reason!
type_tester<decltype(std::abs(0.1))> {}; // double abs(double) overload is selected, as one would expect
}
所以,
int abs(int)
被导入到全局命名空间,而 double abs(double)
没有被导入!为什么?
std::fabs
来处理双精度浮点数,我不知道<cmath>
引入了重载函数。 - MatGC
没有重载,因此当您从全局命名空间调用abs
时,您正在调用带有int
参数的C
函数。当您使用std::
命名空间时,您使用的是 C++,其中重载可用,并且存在std::abs(double)
。 - Marek R