Ambiguity not picked up by the compiler

I had to spend some time searching and fixing the error that I managed to single out in the following code:

#include <iostream> struct A { std::string S; A(const std::string s) { S = s; } }; void f1(A a) { std::cout << "f1:aS = " << aS << "\n"; } void f1(const std::string s) { std::cout << "f1:s = " << s << "\n"; } void f2(A a) { std::cout << "f2:aS = " << aS << "\n"; } int main() { f1(A("test")); f1(std::string("test")); f2(A("test")); f2(std::string("test")); return 0; } 

The error was caused by the missed (by me and the compiler (?)) Ambiguity created by the f1 function: f2 clearly shows that both f1(A) and f1(std::string) are applied to A , but the ambiguity is not selected during compilation by the compiler, and when executed, the output is:

 f1:aS = test f1:s = test f2:aS = test f2:aS = test 

Is this behavior right? Compiler problem? Or just an old PIBCAK?

+3
c ++ ambiguity
Nov 25 '12 at 19:27
source share
1 answer

The behavior you are describing is expected: there is no ambiguity. Congestion resolution ambiguity occurs when two congestions match equally well and are the β€œbest congestion”.

When you call f1 with an argument of type A , the first f1 is an exact match; the second f1 does not match at all. Thus, f1 clearly wins when resolving overload.

When you call f1 with an argument of type std::string , the first f1 matches the conversion constructor A ; the second f1 is an exact match. The second f1 is the best match: this is an exact match, and no conversion is required. Two overloads do not fit equally well, so there is no ambiguity. The second f1 wins during overload resolution.

+8
Nov 25 '12 at 19:33
source share



All Articles