Search code examples
c++jsoncpp

How do I correctly overload methods with two input types `Json::value` and `std:string`?


I have a make() static method in a class Response. It is overloaded to take either std::string or Json::Value from jsoncpp.

I overloaded the method to look like this:

Response::make(Json::Value body)
{
  ...
}

Response::make(std::string body)
{
  ...
}

This causes this error on compilation:

more than one instance of overloaded function "Response::make" matches the argument list:C/C++(308)
main.cpp(15, 20): function "Response::make(std::string body)" (declared at line 28 of "/home/user/weasle/./weasel/./Response.h")
main.cpp(15, 20): function "Response::make(Json::Value body)" (declared at line 36 of "/home/user/weasle/./weasel/./Response.h")
main.cpp(15, 20): argument types are: (const char [33])

Is Json::value treated as a string? How can I fix this issue?


Solution

  • According to the error message, you are passing a const char[33] array (I'm assuming a string literal?) to make(). But, you don't have an overload that accepts that type, so the compiler has to convert it to another type that you do have an overload for.

    However, both std::string and JSON::Value have a constructor that accepts a const char* (which a const char[] decays into), so the compiler doesn't know which overload it should call, hence the error.

    So, you have 2 choices:

    • add a third overload that takes a const char* as input:

      Response::make(const char* body)
      {
        ...
      }
      
      Response::make(Json::Value body)
      {
        ...
      }
      
      Response::make(std::string body)
      {
        ...
      }
      
    • explicitly do the desired conversion yourself at the call site, eg:

      Response::make(Json::Value("..."));
      
      Response::make(std::string("..."));
      

      Alternatively, for std::string in C++14 and later:

      using namespace std::literals;
      Response::make("..."s);