Error call to abs is ambiguous

I'm running a simple C++ program from HackerRank about pointers and it works fine on the website. However, when I run it on MacOS, I get error: call to 'abs' is ambiguous and I'm not sure exactly w...

I’m running a simple C++ program from HackerRank about pointers and it works fine on the website. However,
when I run it on MacOS, I get error: call to 'abs' is ambiguous and I’m not sure exactly what is ambiguous.

I’ve looked at other answers to similar issues, but the error message tends to be Ambiguous overload call to abs(double), which is not the issue I’m having, since I haven’t used any doubles. I’ve also tried including the header files cmath and math.h, but the problem persists.

#include <stdio.h>
#include <cmath>

void update(int *a,int *b) {
    int num1 = *a;
    int num2 = *b;
    *a = num1 + num2;
    *b = abs(num1 - num2);
}

int main() {
    int a, b;
    int *pa = &a, *pb = &b;

    scanf("%d %d", &a, &b);
    update(pa, pb);
    printf("%dn%d", a, b);

    return 0;
}

My issue occurs with line 8.

asked Jul 10, 2019 at 20:43

AkThao's user avatar

14

The full error message is:

$ clang++ test.cpp
test.cpp:8:10: error: call to 'abs' is ambiguous
    *b = abs(num1 - num2);
         ^~~
.../include/c++/v1/math.h:769:1: note: candidate function
abs(float __lcpp_x) _NOEXCEPT {return ::fabsf(__lcpp_x);}
^
.../include/c++/v1/math.h:769:1: note: candidate function
abs(double __lcpp_x) _NOEXCEPT {return ::fabs(__lcpp_x);}
^
.../include/c++/v1/math.h:769:1: note: candidate function
abs(long double __lcpp_x) _NOEXCEPT {return ::fabsl(__lcpp_x);}
^
1 error generated.

The three overloads of abs that you have from <cmath> are abs(float), abs(double) and abs(long double); it’s ambiguous because you have an int argument and the compiler doesn’t know which floating-point type to convert to.

abs(int) is defined in <cstdlib>, so #include <cstdlib> will resolve your problem.

If you’re using Xcode, you can get more details about the error in the Issues navigator (⌘5) and clicking the triangle next to your issue.

answered Jul 10, 2019 at 20:47

zneak's user avatar

zneakzneak

133k41 gold badges253 silver badges322 bronze badges

6

For me, #include <cstdlib> didn’t solve the issue, maybe because I didn’t have to include anything to use abs. So, in case it helps someone else, with explicit casting, it worked well for me like in the next code:

*b = abs(int(num1 - num2));

answered Oct 17, 2020 at 15:19

ana's user avatar

anaana

9777 silver badges12 bronze badges

In templated code, it may be easily overlooked that std::abs is not defined for unsigned types. As an example, if the following method is instantiated for an unsigned type, the compiler may rightfully complain that std::abs is undefined:

template<typename T>
bool areClose(const T& left, const T& right) {
    // This is bad because for unsigned T, std::abs is undefined
    // and for integral T, we compare with a float instead of
    // comparing for equality:
    return (std::abs(left - right) < 1e-7);
}

int main() {
    uint32_t vLeft = 17;
    uint32_t vRight = 18;
    std::cout << "Are the values close? " << areClose(vLeft, vRight) << std::endl;
}

A better definition of areClose() in above code, that would coincidentally also solve the problem of std::abs() being undefined, could look like this:

template<typename T>
bool areClose(const T& left, const T& right) {
    // This is better: compare all integral values for equality:
    if constexpr (std::is_integral<T>::value) {
        return (left == right);
    } else {
        return (std::abs(left - right) < 1e-7);
    }
}

answered Oct 25, 2021 at 20:13

emmenlau's user avatar

emmenlauemmenlau

88811 silver badges17 bronze badges

if your using C compiler you should include

#include <stdlib.h>

and use abs without std::.
If you use C++ compiler then you should change abs to std::abs.

Hope it helps:)

answered Jul 10, 2019 at 20:56

NewMe's user avatar

NewMeNewMe

1624 bronze badges

4

I used #include <bits/stdc++.h> as the only include statement and it worked for me.
My code:

#include <bits/stdc++.h>  
using namespace std;
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int n = nums.size();
        if(n == 0 || n == 1)
            return {};
        vector<int> ans;
        for(int i = 0; i < n; i++)
        {
            if(nums[abs(nums[i])-1] < 0)
                ans.push_back(abs(nums[i]));
            else
                nums[abs(nums[i])-1] = -1 * nums[abs(nums[i])-1];
        }
        return ans;
    }
};

answered Jan 1, 2022 at 6:54

Rajat Singh's user avatar

1

Problem:

You are trying to compile a C/C++ program but you see an error message like

srcmain.cpp:127:21: error: call of overloaded 'abs(uint32_t)' is ambiguous

that refers to a line like

long timedelta = abs(millis() - startTime);

Solution:

Cast the argument to abs() to int or another suitable type:

long timedelta = abs(((int)millis() - startTime));

That should fix the error.

The reason for the error message is that millis() and startTime are both unsigned integers (uint32_t), hence their difference (millis() - startTime) is also an uint32_t. However it makes no sense to compute the abs() of an unsigned integer since the absolute value of an absolute-value integer is  always the same as the input argument.

Then, the compiler tries to cast the uint32_t to any type that is compatible with abs(), like int, float, double, … but it doesn’t know which of those types is the correct one to cast it to.

By saying call of overloaded abs() the compiler is trying to tell you that there are multBiple argument types with which you can call abs(), including intfloat, double, … – a function with the same name but different argument types is called overloaded.

By saying is ambiguous, the compiler is telling you that it doesn’t know which of those variants of abs() it should call.

Note that the compiler does not know that all overloaded variants of abs() fundamentally do the same thing, so it won’t just cast your uint32_t into any arbitrary type. Also, there are tiny details in how the abs() variants work – for example, float abs(float) will do a different calculation compared to double abs(double) since it computes with 32-bit floating point numbers (float) as opposed to 64-bit floating point numbers (double).

Hence, the compiler can’t just assume that they are all the same and it doesn’t matter which one it calls, even though they represent the same underlying mathematical operation

This is happening on Travis’s OS X machines. Full log is here. Details on XCode for this machine is here.

One odd thing is that c++11 should not be enabled and libc++ should not be being linked because -DOSXLIBSTD="libstdc++" is being passed to cmake, but the configure output says:

-- Activating -std=c++11 flag for >= OS X 10.9
-- linking against libc++
[ 22%] Building CXX object CMakeFiles/OSRM.dir/Algorithms/DouglasPeucker.cpp.o
/Users/travis/build/DennisOSRM/node-osrm/Project-OSRM/Algorithms/DouglasPeucker.cpp:102:37: error: 
      call to 'abs' is ambiguous
            const double distance = std::abs(temp_dist);
                                    ^~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/cmath:660:1: note: 
      candidate function
abs(float __x) _NOEXCEPT {return fabsf(__x);}
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/cmath:664:1: note: 
      candidate function
abs(double __x) _NOEXCEPT {return fabs(__x);}
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/cmath:668:1: note: 
      candidate function
abs(long double __x) _NOEXCEPT {return fabsl(__x);}
^
1 error generated.
make[2]: *** [CMakeFiles/OSRM.dir/Algorithms/DouglasPeucker.cpp.o] Error 1

score:11

Accepted answer

The full error message is:

$ clang++ test.cpp
test.cpp:8:10: error: call to 'abs' is ambiguous
    *b = abs(num1 - num2);
         ^~~
.../include/c++/v1/math.h:769:1: note: candidate function
abs(float __lcpp_x) _NOEXCEPT {return ::fabsf(__lcpp_x);}
^
.../include/c++/v1/math.h:769:1: note: candidate function
abs(double __lcpp_x) _NOEXCEPT {return ::fabs(__lcpp_x);}
^
.../include/c++/v1/math.h:769:1: note: candidate function
abs(long double __lcpp_x) _NOEXCEPT {return ::fabsl(__lcpp_x);}
^
1 error generated.

The three overloads of abs that you have from <cmath> are abs(float), abs(double) and abs(long double); it’s ambiguous because you have an int argument and the compiler doesn’t know which floating-point type to convert to.

abs(int) is defined in <cstdlib>, so #include <cstdlib> will resolve your problem.

If you’re using Xcode, you can get more details about the error in the Issues navigator (⌘5) and clicking the triangle next to your issue.

score:-2

I used #include <bits/stdc++.h> as the only include statement and it worked for me.
My code:

#include <bits/stdc++.h>  
using namespace std;
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int n = nums.size();
        if(n == 0 || n == 1)
            return {};
        vector<int> ans;
        for(int i = 0; i < n; i++)
        {
            if(nums[abs(nums[i])-1] < 0)
                ans.push_back(abs(nums[i]));
            else
                nums[abs(nums[i])-1] = -1 * nums[abs(nums[i])-1];
        }
        return ans;
    }
};

score:1

if your using C compiler you should include

#include <stdlib.h>

and use abs without std::.
If you use C++ compiler then you should change abs to std::abs.

Hope it helps:)

score:1

In templated code, it may be easily overlooked that std::abs is not defined for unsigned types. As an example, if the following method is instantiated for an unsigned type, the compiler may rightfully complain that std::abs is undefined:

template<typename T>
bool areClose(const T& left, const T& right) {
    // This is bad because for unsigned T, std::abs is undefined
    // and for integral T, we compare with a float instead of
    // comparing for equality:
    return (std::abs(left - right) < 1e-7);
}

int main() {
    uint32_t vLeft = 17;
    uint32_t vRight = 18;
    std::cout << "Are the values close? " << areClose(vLeft, vRight) << std::endl;
}

A better definition of areClose() in above code, that would coincidentally also solve the problem of std::abs() being undefined, could look like this:

template<typename T>
bool areClose(const T& left, const T& right) {
    // This is better: compare all integral values for equality:
    if constexpr (std::is_integral<T>::value) {
        return (left == right);
    } else {
        return (std::abs(left - right) < 1e-7);
    }
}

score:5

For me, #include <cstdlib> didn’t solve the issue, maybe because I didn’t have to include anything to use abs. So, in case it helps someone else, with explicit casting, it worked well for me like in the next code:

*b = abs(int(num1 - num2));

Related Query

  • What is an undefined reference/unresolved external symbol error and how do I fix it?
  • How to fix the error «Windows SDK version 8.1» was not found?
  • How to fix GCC compilation error when compiling >2 GB of code?
  • What is an ‘undeclared identifier’ error and how do I fix it?
  • How to fix Genymotion in linux ElementaryOS with error `CXXABI_1.3.8′ not found
  • Strange ambiguous call to overloaded function error
  • error MSB3073: How do I fix this?
  • How do I fix unexpected end of file error with pch.h
  • How to fix ‘expected primary-expression before’ error in C++ template code?
  • What is a glibc free/malloc/realloc invalid next size/invalid pointer error and how to fix it?
  • How to fix «error: call to ‘abs’ is ambiguous»
  • Ambiguous call to abs
  • Why is the constructor in this C++ code ambiguous and how do I fix it?
  • Obviously ambiguous call does not cause a compilation error on GCC
  • How to diagnose ambiguous call to sqrt(int&) in g++ 4.3.4
  • How to fix unknown command error in CMake, when I using Conan?
  • How to fix distcc error
  • How do I fix a «no matching function for call to ‘atoi'» error?
  • How do I fix this error with allocation and deallocation mismatch?
  • how to fix the error c2118: negative subscript
  • How to fix «Could not find a package configuration file …» error in CMake?
  • How to fix JsonCPP error from getMemberNames()?
  • How to fix this C3848 error on vs2013?
  • How to fix «error: no matching function for call to» when inheriting twice from a base class
  • How to fix the C++ preprocessor «/lib/cpp» fails sanity check error when configure PHP 7.0.1
  • How to fix an «field has incomplete type» error when using a forward declaration
  • How to compile programm with error «no matching function for call to ‘to_string'»? c++
  • How to fix «undefined reference» compiler error
  • How to fix compile error «This function or variable may be unsafe» (strcpy)
  • How to fix backtrace line number error in C++

More Query from same tag

  • boost::Spirit Grammar for unsorted schema
  • SDL2 on Arch Linux: window renders what’s on the screen behind it
  • Recursive rule in Spirit.X3
  • c++ execute code from no file system
  • Motion tracker using Raspberry pi 3, OpenCV and Python
  • Implement matlab code in C++?
  • Qt — is there a way to transform a graphic item into a pixmap?
  • What is the difference between square bracket arrays and pointer arrays?
  • opencv facial sdk support
  • Automatic binding for boost::thread in C++?
  • CLion is automatically printing back input from standard input, is there any fix for this?
  • Accessing class object from multiple threads
  • Caffe C++ set data in input layer
  • Linker error for variadic template
  • Macro Operator List
  • Matrix Algebra Using C++
  • Are there any equivalents to the futex in Linux/Unix?
  • How to use std::thread of C++ 11 under Cygwin GCC 4.7.2
  • Difference between & and * in function parameters
  • Can I assign multiple threads to a code section in OpenMP?
  • Removing duplicates from a non-sortable vector
  • What’s the Meaning of Texture Coordinate in obj Files
  • C++ boost sleep accuracy
  • What does pragma keylist keyword do?
  • Extracting calling convention from a function type using template metaprogramming in c++
  • Is it legal to write code like C#?
  • Java’s popularity in Internet Algorithmics (Search, Big Data etc.)
  • System where 1 byte != 8 bit?
  • How can I detect when I’m on a system running Unity?
  • operator << (stream output) for nullptr

lily19

0 / 0 / 0

Регистрация: 30.09.2016

Сообщений: 11

1

14.10.2016, 14:18. Показов 11153. Ответов 6

Метки нет (Все метки)


помогите пожалуйста, выдает ошибку. не знаю где

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
int main()
{double x,y;
cin>>x;
if( x>113) { y= (pow(sin(x),2)*(log(3*x*x-x*2)/log(0.3))*((x+3)/(abs(x))));}
if(x<113) { y=(abs(x-88.5)*exp((-x)*x));}
else {y=((x+3)/abs(x));}
cout<<"y="<<y;
getchar();
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

14.10.2016, 14:18

6

7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

14.10.2016, 14:53

2

Работает. Где ошибка?



0



lily19

0 / 0 / 0

Регистрация: 30.09.2016

Сообщений: 11

14.10.2016, 14:57

 [ТС]

3

я писала в dev и в онлайн компиляторе в c++shell. ошибка была показана тут:

C++
1
2
3
if( x>113) { y= (pow(sin(x),2)*(log(3*x*x-x*2)/log(0.3))*((x+3)/(abs(x))));}
if(x<113) { y=(abs(x-88.5)*exp((-x)*x));}
else {y=((x+3)/abs(x));}



0



0 / 0 / 0

Регистрация: 13.10.2016

Сообщений: 5

14.10.2016, 14:59

4

abs замени на fabs



0



lily19

0 / 0 / 0

Регистрация: 30.09.2016

Сообщений: 11

14.10.2016, 19:48

 [ТС]

5

мелочь, а важно..спасибо.мне помогло))

Добавлено через 4 часа 43 минуты
если не сложно… первый раз пишу код логической задачи. ошибок не выдает но я все сделал интуитивно. есть данные которые необходимо ввести и ответ. ответ у меня в итоге не совпал …

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<math.h>
#include<stdio.h>
using namespace std;
int main()
{ bool x,y,z,A,B,D,F,E;
cin>>x>>y>>A>>B>>F>>E;
D= (((log(cos(sqrt(x)+exp((-4)*x)))/log(4))/30) >((x-y)+B)||(3*x+sin(3.14159265359*x)-40 >= ((x-2*y)+!A))&&(tan(x/2)/25==((2*x-y)+B)));
E=((x*x*x*x-40)>((x-3*y)+!A) && ((log(15*x*x)/log(5))>=((3*x-y)+B)));
F=((abs(x+y*y)-40)==((3*x-2*y)+!A)&&25);
z= D||E||F;
cout<<"z="<<z;
getchar();
}



0



Падаван С++

447 / 261 / 89

Регистрация: 11.11.2014

Сообщений: 916

14.10.2016, 19:59

6

Цитата
Сообщение от lily19
Посмотреть сообщение

z= D||E||F;

, какой ответ вы ожидаете в этой строке ?



0



GbaLog-

14.10.2016, 20:12


    Исправить ошибку «call of overloaded ‘abs(double&)’ is ambiguous»

Не по теме:

Цитата
Сообщение от lily19
Посмотреть сообщение

я писала

Цитата
Сообщение от lily19
Посмотреть сообщение

я все сделал

Кто же Вы? :scare:



0



  • Forum
  • Beginners
  • Problem with abs() in a program.

Problem with abs() in a program.

Hi all,

I’m using Herb Schildt’s C++ Beginners Guide, using this program from Module 1 Mastery:

// Average the absolute values of 5 numbers.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i;
double avg, val;
avg = 0.0;
for(i=0; i<5; i++) {
cout << «Enter a value: «;
cin >> val;
avg = avg + abs(val);
}
avg = avg / 5;
cout << «Average of absolute values: » << avg;
return 0;
}

The line in bold is giving me an error in the Dev++ compiler:

In function `int main()’:
call of overloaded `abs(double&)’ is ambiguous
candidates are: int abs(int)
long long int __gnu_cxx::abs(long long int)
long int std::abs(long int)

The program above is copied directly from the book — is there an error in the program?

Many thanks…

Last edited on

Hi could you just add #include <cmath> and check if it is working or not ?

Blimey, well I never. To be honest, Moschops, I’m only about 60 pages into this book and I’ve spotted several errors, or what I think are errors.

For example, he has a table that shows this:
int -2,147,483,648 to 2,147,483,647
unsigned int -2,147,483,648 to 2,147,483,647
signed int 0 to 4,294,967,295
short int -32,768 to 32,767
unsigned short int -32,768 to 32,767
signed short int 0 to 65,535

and I’m sure the figures for unsigned int and signed int, and unsigned short int and signed short int are the wrong way around.

So Dev-C++ hasn’t been updated in 6 yrs — perhaps I’ll look at one of the alternatives.

Thanks for your response Moschops, much appreciated.

Having said all that, I added #include <cmath> as suggested by acpaluri, and it has worked!

Cheers acpaluri, much appreciated :)

The abs in cmath will be similarly ambiguous. In this case, he’s getting abs from cstdlib.

Last edited on

Hmmm…you’ll obviously know a lot more than me, I’m a total novice — but it’s working without any errors after adding that header in…

I’m confused — maybe Herb’s confused me ;-)

My mistake; there is an abs in cmath that accepts double — the page http://www.cplusplus.com/reference/clibrary/cmath/ lists it on the left, but not in the tables in the middle, and I missed it.

Herb explains very clearly and in an easy to follow way things that are unfortunately wrong.

Last edited on

Delete } on 14 row.

Topic archived. No new replies allowed.

Заголовок <math.h> является заголовком библиотеки C std. Он определяет множество вещей в глобальном пространстве имен. Заголовок <cmath> — это версия этого заголовка для C ++. Он определяет, по сути, то же самое в пространстве имен std. (Есть некоторые отличия, например, версия для C ++ поставляется с перегрузками некоторых функций, но это не имеет значения.) Заголовок <cmath.h> не существует.

Поскольку производители не хотят поддерживать две версии того, что по сути является одним и тем же заголовком, они придумали разные возможности иметь только одну из них за кулисами. Часто это заголовок C (поскольку компилятор C ++ может его анализировать, а обратное не работает), а заголовок C ++ просто включает его и переносит все в пространство имен. std. Или есть магия макросов для разбора одного и того же заголовка с или без namespace std обернут или нет. К этому добавьте, что в некоторых средах неудобно, если заголовки не имеют расширения файла (например, редакторы не могут выделить код и т. Д.). Таким образом, некоторые поставщики <cmath> быть однострочным, включая другой заголовок с .h расширение. Или некоторые будут отображать все, включая соответствие <cblah> в <blah.h> (который с помощью макро-магии становится заголовком C ++, когда __cplusplus определен, и в противном случае становится заголовком C) или <cblah.h> или что-то еще.

Вот почему на некоторых платформах, включая такие вещи, как <cmath.h>, который не должен существовать, сначала будет успешным, хотя позже это может привести к серьезному сбою компилятора.

Я понятия не имею, какую реализацию std lib вы используете. Я полагаю, что это тот, который поставляется с GCC, но этого я не знаю, поэтому я не могу точно объяснить, что произошло в вашем случае. Но это, безусловно, смесь одного из вышеупомянутых хаков, связанных с конкретными поставщиками, и вы включаете заголовок, который вам не следовало включать. Может это тот, где <cmath> карты для <cmath.h> с конкретным (набором) макросов, которые вы не определили, так что вы получили оба определения.

Обратите внимание, однако, что этот код по-прежнему не должен компилироваться:

#include <cmath>

double f(double d)
{
  return abs(d);
}

Не должно быть abs() в глобальном пространстве имен (это std::abs()). Однако, согласно описанным выше уловкам реализации, вполне может быть. Перенос такого кода позже (или просто попытка скомпилировать его со следующей версией вашего поставщика, которая не позволяет этого) может быть очень утомительно, поэтому вы должны следить за этим.

Почему я должен получить эту ошибку

 C2668: 'abs' : ambiguous call to overloaded function

Для простого кода, подобного этому

#include <iostream>
#include <cmath>
int main()
{
unsigned long long int a = 10000000000000;
unsigned long long int b = 20000000000000;
std::cout << std::abs(a-b) << "n";   // ERROR
return 0;
}

Ошибка по-прежнему присутствует после удаления std::, Однако, если я использую int Тип данных (с меньшими значениями) нет проблем.

Традиционное решение — проверить это вручную

std::cout << (a<b) ? (b-a) : (a-b) << "n";

Это единственное решение?

4

Решение

Проверка кажется единственным действительно хорошим решением. Альтернативы требуют, чтобы тип, больше чем Ваш и нестандартное расширение, использовал это.

Вы можете пойти с решениями, приводящими к подписанному длинному, если ваш диапазон соответствует. Я бы вряд ли предложил такой способ, особенно если реализация находится в функции, которая делает только это.

10

Другие решения

Вы в том числе <cmath> и, таким образом, используя «плавающая запятая abs».

«целое число abs«объявлен в <cstdlib>,

Тем не менее, нет перегрузки для unsigned long long int (и то и другое a а также b являются, таким образом, a-b тоже), а перегрузка для long long int существует только с C ++ 11.

5

Во-первых, вам нужно включить правильный заголовок. Как указывает gx_, <cmath> имеет abs с плавающей точкой, и на моем компиляторе он фактически компилируется, но результат, вероятно, не тот, который вы ожидали:

1.84467e+19

Включают <cstdlib> вместо. Теперь ошибка:

main.cpp:7:30: error: call of overloaded ‘abs(long long unsigned int)’ is ambiguous
main.cpp:7:30: note: candidates are:
/usr/include/stdlib.h:771:12: note: int abs(int)
/usr/include/c++/4.6/cstdlib:139:3: note: long int std::abs(long int)
/usr/include/c++/4.6/cstdlib:173:3: note: long long int __gnu_cxx::abs(long long int)

Как видите, нет unsigned перегрузка этой функции, потому что вычисление абсолютного значения чего-то типа unsigned не имеет смысла.

Я вижу ответы, предлагающие вам сыграть unsigned введите подписанный, но я считаю, что это dagereous, если вы действительно не знаете, что делаете!
Позвольте мне сначала спросить, каков ожидаемый диапазон значений a а также b что вы собираетесь оперировать? Если оба ниже 2^63-1 Я настоятельно рекомендую просто использовать long long int, Если это не так, позвольте мне отметить, что ваша программа для значений:

a=0, b=1

а также

a=2^64-1, b=0

будет производить точно такой же результат, потому что на самом деле вам нужно 65 бит, чтобы представить любой возможный результат разницы 2 64-битных значений. Если вы можете подтвердить, что это не будет проблемой, используйте приведенный состав как предложено. Однако, если вы не знаете, возможно, вам придется переосмыслить то, чего вы на самом деле пытаетесь достичь.

1

Поскольку до C ++ с C вы привыкли использовать abs, fabs, labs для каждого отдельного типа, c ++ допускает перегрузку abs, в этом случае он не понимает или не доволен вашей перегрузкой.

использование labs(a-b) видя, как вы используете длинные, это должно решить вашу проблему.

-2

I have a custom data type that in practice can be either float or double. On every OS except OSX, I am able to successfully build this C++11 template:

#include <cmath>
#include <cstdlib>
#include <cstdint>

template< class REAL_T >
inline REAL_T inhouse_abs(REAL_T i_val)
{
    return std::abs((REAL_T)i_val);
}

int main()
{
    int32_t ui = 2;
    inhouse_abs(ui);
    return 0;
}

However, clang 6.0 (3.5 LLVM) reports an ambiguous function call. If I change abs to fabs, the error is resolved on OSX, but now an identical error shows up on my Linux clang, gcc, and Visual Studio.

Error on Visual Studio with fabs:

349 error C2668: 'fabs' : ambiguous call to overloaded function

UPDATE

This example compiled on our OS X systems, although in the nearly identical project it does not. The solution was including <cstdlib> explicitly in the source, rather than back in another header. The reason is unclear, but seems to be xcode/clang not following our header includes properly.


The issue is that libc++ is not entirely C++11 compliant with the integral overload for std::abs in cmath:

double      fabs( Integral arg ); (7)   (since C++11)

Including cstdlib solves your problem since that header has overloads specifically for integer types.

For reference the draft C++11 standard section 26.8 [c.math] paragraph 11 says:

Moreover, there shall be additional overloads sufficient to ensure:

and includes the following item:

  1. Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double.

This is situation very likely to change due to LWG active issue 2192: Validity and return type of std::abs(0u) is unclear. I am guessing libc++ choose not to provide the overloads in cmath due to the issue brought up in this defect report.

See Is std::abs(0u) ill-formed? for more details on this.

Понравилась статья? Поделить с друзьями:
  • Error call hotline перевод
  • Error calculating max stack value
  • Error caching lexicon topic lexicon ru core resource
  • Error cached plan must not change result type
  • Error cache miss php