Function reference ambiguous

Why does a compiler error occur stating that my links are ambiguous? I have float , int and string that should create separate function signatures, right?

Here is what I still have:

 #include <iostream> #include <string> using namespace std; int plus(int a, int b); float plus(float a, float b); string plus(string a, string b); int main(void) { int n = plus(3, 4); double d = plus(3.2, 4.2); string s = plus("he", "llo"); string s1 = "aaa"; string s2 = "bbb"; string s3 = plus(s1, s2); } int plus(int a, int b) { return a+b; } // int version float plus(float a, float b) { return a+b; } // float version string plus(string a, string b) { return a+b; } // string version 
+7
source share
2 answers

First, do not use using namespace std; . In this case, there is a structure called std::plus -oh, wait, no matter what is actually called plus and its constructor is thrown into the bucket to allow overloading using the plus function.


Secondly, you have ambiguity, because 3.2 and 4.2 are of type double and can convert equally well to float or int .

This is a simplification, but when it comes to passing numbers to an overloaded function, C ++ basically uses these rules:

  • If all arguments exactly match one of the overloads, use this one.
  • If all arguments can be raised to fit one of the overloads, use this one.
  • If all arguments can be numerically converted to match one of the overloads, use this one.

If you have several candidates at a certain level, then this is ambiguity. Rarely, a double does not advance to float , which would be a drop. Therefore, it should use the standard conversion in float , which is associated with the standard conversion with int , so these two overloads are ambiguous.

+15
source

Call float overload as follows:

 double d = plus(3.2f, 4.2f); 

A constant like 3.2 does have a double .

+4
source

All Articles