view raw
RPGillespie RPGillespie - 9 months ago 41
C++ Question

Overloaded Bool/String Ambiguity

Why is C++ casting the string literal I pass in as a bool rather than a string?

#include <iostream>

using namespace std;

class A
A(string v)
cout << v;

A(bool v)
cout << v;

int main()
return 0;


Is it because the compiler isn't smart enough to make the jump from char * to string and rather just assumes that bool is the closest thing to a pointer? Is my only option to make an explicit char * constructor that basically does the exact same thing as the string constructor?


If you have C++11 you can use a delegating constructor:

A(char const* s) : A(std::string(s)) { }

The reason the boolean converting-constructor is chosen over the one for std::string is because the conversion from char const* to bool is a standard conversion while the one to std::string is a user-defined conversion. Standard conversions have a greater rank than user-defined conversions.