Overloaded Bool/String Ambiguity

前端 未结 4 984
陌清茗
陌清茗 2021-01-02 04:57

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

#include 

using namespace std;

class A
{
    public:
              


        
4条回答
  •  悲哀的现实
    2021-01-02 05:55

    Recently I passed this problem too, let me share another way.

    You can change the bool constructor to a unsigned char. So the decay and implict conversion of string literal don't happen, and the std::string constructor takes place.

    class A
    {
    public:
        A(string v)
        {
            cout << v;
        }
    
        A(unsigned char v)
        {
            cout << static_cast(v);
        }
    };
    
    int main()
    {
         A("Hello"); // <- Call A(string)
         A(false);   // <- Call A(unsigned char)
    }
    

    This way you don't need to provide always overloads to std::string and const char* neither making code bloat constructing the std::string at the client call site.

    I don't claim that's better, but it's simpler.

提交回复
热议问题