user3475622
user3475622

Reputation: 33

c++ function overload ambiguous without automatic type conversion

My question is why automatic type conversion does not work when calling overloaded functions in c++. Example code is below:

void test(char t);
void test(short t);
void test(long long t);

void main(){
    int a=8;
    test(a);
}

If I compile codes above with g++/clang++, an error of function overload ambiguous would occur at

test(a)

Why not the compiler apply automatic type conversion rules here? Variable a in function main() is type of int which should be conversed into type long long to avoid loss of precision. I don't want to write duplicated function for type int or long. Of course I could avoid the error with explicit cast below:

test((long long)a)

However, do I have to use explicit cast every time I need to call test(long long) for parameters of type int or long? Is there any way of making the compiler more smarter?

Thank you for the answers.

Upvotes: 3

Views: 1130

Answers (2)

Vlad Sydorenko
Vlad Sydorenko

Reputation: 106

In short - yes, you have to cast explicitly each time.

In you case, the problem is that you have more than one possible type conversion. int could be implicitly converted in all three types you have (char, short, long long). So compiler can't determine what type conversion to use in this case.

You could read more about implicit type conversions here http://en.cppreference.com/w/cpp/language/implicit_conversion

You can achieve you goal with templates:

// any type that hasn't explicit definition
template <typename T = long long>
void test(T t);

// process char differently
void test(char c);

// process short differently
void test(short c);

It's surely UNSAFE but possible. I advice you to add static assert inside your template function.

Upvotes: 2

Hariom Singh
Hariom Singh

Reputation: 3632

Any automatic type conversion is an implicit conversion if not done explicitly in the source code.The Values of integral types narrower than int (char, signed char, unsigned char, short int and unsigned short) is promoted to int

so when you do this it get confused which one to call (as both implicitly becomes void test (int t)

void test(char t);
void test(short t);

int main(){
    int a=8;
    test(a);

}

But when you send the exact data type info no confusion

#include<iostream>


void test(int  t);
void test(short t);
void test(long long t);

int main(){
    int a=8;
    test(a);
}

If you will leave on compiler to decide definitely you will be in problem

Follow the link to stop implicit conversion

Stop Implicit conversion

Upvotes: 2

Related Questions