[vtk-developers] Dashboard problems: ambiguous conversion fabs() call

Kyle Lutz kyle.lutz at kitware.com
Thu Aug 16 11:14:55 EDT 2012


On Thu, Aug 16, 2012 at 8:01 AM, David Gobbi <david.gobbi at gmail.com> wrote:
> On Thu, Aug 16, 2012 at 8:35 AM, Kyle Lutz <kyle.lutz at kitware.com> wrote:
>> On Thu, Aug 16, 2012 at 6:58 AM, David Gobbi <david.gobbi at gmail.com> wrote:
>>> On Thu, Aug 16, 2012 at 7:39 AM, Kyle Lutz <kyle.lutz at kitware.com> wrote:
>>>>
>>>> Also, did you mean std::abs()? std::fabs() is not overloaded for the
>>>> integral types and std::abs() should be preferred anyway.
>>>
>>> In code that is only meant to be used for floating-point numbers, I
>>> prefer std::fabs() because I _like_ the fact that it produces an error
>>> if an integer slips in. But for vtkTuple, where both ints and floats
>>> are possible, std::abs() is the clear winner.
>>
>> I see your point.
>>
>> However, you will not receive an error when you pass an integer to
>> std::fabs(). The integer will just be converted to a floating-point
>> type before being passed to the function.
>>
>> For example try the following code:
>>
>> int i = -42;
>> std::cout << std::fabs(i) << std::endl;
>
> If std::fabs() only has overloads for float, double, long double
> (as is the case on some compilers) then your example code
> will fail to compile.  In general I don't think that std::fabs()
> is templated, it's just overloaded for different arg types, in
> which case it will give the same error as the following code:
>
> float myfabs(float x) { return std::fabs(x); }
> double myfabs(double x) { return std::fabs(x); }
>
> int main(int argc, char *argv[])
> {
>   int i = -42;
>   std::cout << myfabs(i) << std::endl;
>
>   return 0;
> }

Correct. But GCC and clang both do provide a std::fabs() for integral
types. Here's the implementation from GCC's cmath:

template<typename _Tp>
    inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
					   double>::__type
    abs(_Tp __x)
    { return __builtin_fabs(__x); }

I guess my point is that if you want to enforce that your template
class/function is only used with floating-point types then you should
probably check for that condition directly rather than relying on
std::fabs() failing to compile.

Just out of curiosity, what compiler are you using?

-kyle



More information about the vtk-developers mailing list