'fabs':使用模板时对重载函数的模棱两可的调用 [英] 'fabs' : ambiguous call to overloaded function when using templates

查看:70
本文介绍了'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;
}

T 可以是 int double float 等.

编译器给我'fabs':使用模板时对重载函数的模棱两可的调用

有什么问题,如何解决?

What's the problem and how can it be solved ?

谢谢.

推荐答案

T 可以是 int ,double, float 等.

T can be int, double, float, etc.

在C ++中, float double long double 的三个 std :: fabs 重载

There are three overloads of std::fabs in C++ for float, double, and long double.

如果尝试使用类型为 int 的参数调用 std :: fabs ,由于重载歧义,您将收到编译错误. int 参数平等地匹配所有三个可用的重载.

If you try to call std::fabs with an argument of type int, you will get a compilation error due to an overload ambiguity. An int argument matches all three of the available overloads equally.

您可以将参数转换为已知类型(例如 double long double ),这可以解决歧义,或者可以将调用包装到模板中的fabs 对整数类型的参数进行歧义消除.

You could cast the argument to a known type (e.g. double or long double), which would resolve the ambiguity, or you could wrap the call to fabs in a template that performs disambiguation for integer-type arguments.

或者,C ++具有 std :: abs ,对于整数和浮点类型(在< cmath> < cstdlib>中声明; ).此外,如果您最近有一个实现C ++ 11的标准库实现,则使用整数类型参数调用 std :: fabs 会将其自动转换为 double ,因此没有歧义.

Alternatively, C++ has std::abs, which is overloaded for both integer and floating point types (declared in <cmath> and <cstdlib>). Further, if you have a recent Standard Library implementation that implements C++11, a call to std::fabs with an integer type argument will automatically convert the argument to type double, so there is no ambiguity.

这篇关于'fabs':使用模板时对重载函数的模棱两可的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆