相关疑难解决方法(0)

intabs(int) 与 doubleabs(double)

我想从 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)不是!

为什么?

c++ cmath language-lawyer

5
推荐指数
2
解决办法
372
查看次数

'fabs':使用模板时对重载函数的模糊调用

我有以下功能:

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++

0
推荐指数
1
解决办法
4890
查看次数

如何编写C++模板函数来内部调用多个C函数?

我希望编写一个C++模板函数,该函数反过来使用一些"C"函数并利用函数重载.

例如,我需要myAbs使用模板编写一个函数,这些模板根据输入参数类型进行适当的调用fabsabs定义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>.

c c++ templates overloading

0
推荐指数
1
解决办法
112
查看次数

标签 统计

c++ ×3

c ×1

cmath ×1

language-lawyer ×1

overloading ×1

templates ×1