Function/Method Overloading C++: Data type confusion?

前端 未结 7 2507
清酒与你
清酒与你 2021-02-14 18:11

I\'m having some trouble overloading methods in C++. As an example of the problem, I have a class with a number of methods being overloaded, and each method having one parameter

7条回答
  •  醉话见心
    2021-02-14 18:46

    The order makes no difference. The method to call is selected by analyzing the types of arguments and matching them to the types of parameters. In case there's no exact match, the best-matching method is selected. In your case it happens to be the bool method.

    You are supplying an argument of type const char[7]. According to the C++ overloading rules, the best path here is to let const char[7] decay to const char * and then convert it to bool using a standard conversion. The path with converting to std::string is considered worse, since it would involve a user-defined conversion from const char * to std::string. Generally, user-defined conversions lose overload resolution process to standard conversions. This is what happens in your case as well.

    If you need std::string version to be called here, provide an explicit overload for const char * type, and delegate the call to std::string version by converting the argument to std::string type explicitly

    void Method(const char *paramater /* sic! */)
    {
      Method(std::string(paramater));
    }
    

提交回复
热议问题