我想从 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
}
Run Code Online (Sandbox Code Playgroud)
所以,int abs(int)是导入到全局命名空间,而double abs(double)不是!
为什么?
我有以下功能:
T* tContainer_t<T, R>::Remove( T item )
{
typename R::const_iterator it = std::find_if(Container.begin(), Container.end(), [item](const T* v) { return std::fabs(*v - item) < DBL_EPSILON; });
if (it != Container.end())
{
...
}
else
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
T可以int,double,float,等....
编译器给了我 'fabs' : ambiguous call to overloaded function when using templates
问题是什么?如何解决?
谢谢.
我希望编写一个C++模板函数,该函数反过来使用一些"C"函数并利用函数重载.
例如,我需要myAbs使用模板编写一个函数,这些模板根据输入参数类型进行适当的调用fabs或abs定义math.h.这该怎么做?
#include <math.h>
template<typename T>
T abs(T x)
{
// I need to write an efficient code here!
// If it is 'double' and 'float' I may be able to compare the
// sizeof(Type) and call 'return fabs(x)' or 'return abs(x)'.
// But this is not a good solution as two types can be of same size!
}
Run Code Online (Sandbox Code Playgroud)
注意:我只是用它作为例子来解释我的问题.我已经知道这样的功能"abs"已经可用了<cmath>.