4

Consider following program: (See live demo here http://ideone.com/7VHdoU )

#include <iostream> void fun(int*)=delete; void fun(double)=delete; void fun(char)=delete; void fun(unsigned)=delete; void fun(float)=delete; void fun(long int); int main() { fun(3); } void fun(long int a) { std::cout<<a<<'\n'; } 

Compiler is giving following error:

error: call of overloaded 'fun(int)' is ambiguous fun(3); ^ 

But I don't understand why & how it is ambiguous? Does it involve any kind of automatic type promotion here? I know that calling fun with (3L) makes compilation successful.

4
  • 9
    It's ambiguous because none of the functions you have declared take a plain int, and the compiler cannot choose whether to convert to double, char, unsigned int, float or long int. deleted functions still participate in overload resolution. Commented Oct 21, 2015 at 4:31
  • 1
    @user657267 i think you can add it as an answer :) Commented Oct 21, 2015 at 4:35
  • 1
    @user657267: Better if you add it as an answer so I can accept it. Commented Oct 21, 2015 at 4:38
  • 1
    @user657267 is right Commented Oct 21, 2015 at 4:38

1 Answer 1

2

Probably 3 can be interpreted as other types (like char, unsigned...), so it might be ambiguous for the compiler to know what function you want to call. You need to indicate value 3 is a long int.

#include <iostream> void fun(int*)=delete; void fun(double)=delete; void fun(char)=delete; void fun(unsigned)=delete; void fun(float)=delete; void fun(long int); int main() { fun((long int)3); } void fun(long int a) { std::cout<<a<<'\n'; } 
Sign up to request clarification or add additional context in comments.

6 Comments

or call it like this: fun(3L)
@PravasiMeet Yeah sure. As long as you make the compiler not confuse what to call.
avoid "C" style casting in C++. Prefer static_cast<long int>
@Krypton, that comment should have been an answer, in which case your answer wouldn't have been necessary. But they didn't, so your answer is relevant. However, why cast when you can simply make the type? I'm sure the compiler is smart enough to do the right thing, but it's much better practice to use the correct type in the first place.
@Nandu: personally I think C-style casts are better for simple scalar types - the C++ equivalent is more verbose and has no obvious advantages. YMMV of course.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.