'fabs' : ambiguous call to overloaded function when using templates

后端 未结 1 1029
孤街浪徒
孤街浪徒 2021-01-07 14:47

I have the following function:

T* tContainer_t::Remove( T item )
{    
    typename R::const_iterator it = std::find_if(Container.begin(), Contai         


        
相关标签:
1条回答
  • 2021-01-07 15:27

    T can be int, double, float, etc.

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

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题