views:

88

answers:

1

Why does VisualC++ (2008) get confused 'C2666: 2 overloads have similar conversions' when I specify an enum as the second parameter, but not when I define a bool type?

Shouldn't type matching already rule out the second constructor because it is of a 'basic_string' type?

#include <string>
using namespace std;

enum EMyEnum { mbOne, mbTwo };
class test {
public: 
#if 1 // 0 = COMPILE_OK, 1 = COMPILE_FAIL
    test(basic_string<char> myString, EMyEnum myBool2) { }
    test(bool myBool, bool myBool2) { }
#else
    test(basic_string<char> myString, bool myBool2) { }
    test(bool myBool, bool myBool2) { }
#endif
};

void testme() {
    test("test", mbOne);
}

I can work around this by specifying a reference 'ie. basic_string &myString' but not if it is 'const basic_string &myString'.

Also calling explicitly via "test((basic_string)"test", mbOne);" also works.

I suspect this has something to do with every expression/type being resolved to a bool via an inherent '!=0'.

Curious for comments all the same :)

+5  A: 

The reason for the ambiguity is that one candidate function is better than another candidate function only if none of its parameters are a worse match than the parameters of the other.

The problem is that the string literal, which has a type of const char[5] is convertible to both std::string (via a converting constructor) and to a bool (since an array can decay to a pointer, and any pointer is implicitly convertible to bool). The conversion to bool is preferred because it is a standard conversion and standard conversions are preferred to user-defined conversions.

So, consider the "broken" overloads:

test(basic_string<char> myString, EMyEnum myBool2) { }  // (1)
test(bool myBool, bool myBool2) { }                     // (2)

The first argument is a const char[5] and prefers (2) (per the description above). The second argument is an EMyEnum and prefers (1), which is an exact match; a conversion would be required to match (2) (an enumeration can be implicitly converted to a bool).

Now consider the second case:

test(basic_string<char> myString, bool myBool2) { }    // (3)
test(bool myBool, bool myBool2) { }                    // (4)

The first argument still prefers (4), but now the second argument can match both (3) and (4) equally. So, the compiler can select (4) and there is no ambiguity.

There would be no ambiguity if you eliminated the required conversion for the first argument, e.g.,

test(basic_string<char>("test"), mbOne);

because both arguments would match (1) exactly.

James McNellis