Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not able to compile code with unsigned and signed overloads of a function

I was trying to write an overloaded function to accept both signed and unsigned integers.

Following is my code:

#include <iostream>

void fun(const long long a)
{
    std::cout << "Signed: " << a << std::endl;
}

void fun(const unsigned long long a)
{
    std::cout << "unsigned: " << a << std::endl;
}

int main()
{
    unsigned int v = 10;
    fun(v);
    return 0;
}

This gives the following compilation error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

main.cpp:17:5: error: call to 'fun' is ambiguous
    fun(v);
    ^~~
main.cpp:4:6: note: candidate function
void fun(const long long a)
     ^
main.cpp:9:6: note: candidate function
void fun(const unsigned long long a)
     ^
1 error generated.

I was assuming it would work just fine, as unsigned int can be represented by the unsigned long long type.

Can anyone please help me understand this error?

>Solution :

In general, an unsigned integer can be implicitly converted to an (un)signed integer of larger size without any data loss. And (un)signed long long is larger than an unsigned int in most implementations.

Since unsigned int is implicitly convertible to both long long and unsigned long long, the compiler doesn’t know which overload you want to call, hence the error. So, you will have to explicitly tell it which overload to use, eg:

fun(static_cast<unsigned long long>(v));

Or

static_cast<void (*)(const unsigned long long)>(fun)(v);

Or

void (*f)(const unsigned long long) = fun;
f(v);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading