Skip to content

explicit conversion to string not considered for std::map keys in GCC8 #2096

Description

@ottojo
  • What is the issue you have?
    Compilation fails with GCC8 when trying to serialize a std::map whose Key-type provides explicit conversion to std::string

  • Please describe the steps to reproduce the issue. Can you provide a small but working code example?

#include <iostream>
#include <nlohmann/json.hpp>

class ID {
public:
    explicit ID(int i) : id(i) {};

    explicit operator std::string() const {
        return std::to_string(id);
    }

    bool operator<(const ID &rhs) const {
        return id < rhs.id;
    }

private:
    int id;
};

int main() {
    std::map<ID, std::string> map = {
            {ID(7),  "test1"},
            {ID(13), "test2"}
    };

    nlohmann::json mapJson = map;
    std::cout << mapJson.dump(4) << std::endl;
 }
  • What is the expected behavior?
    Serialization to
{
    "13": "test2",
    "7": "test1"
}
  • And what is the actual behavior instead?
    Does not compile when using gcc version 8
g++-8 (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0

Compiler error:

no known conversion for argument 2 from ‘std::pair<const ID, std::__cxx11::basic_string<char> >::first_type’ {aka ‘const ID’} to ‘const key_type&’ {aka ‘const std::__cxx11::basic_string<char>&’}
  • Which compiler and operating system are you using? Is it a supported compiler?

    • I found this issue only when compiling with GCC 8.4.0
    • Other compilers tested:
      • g++-9 (Ubuntu 9.3.0-11ubuntu0~18.04.1) 9.3.0
      • g++-10 (Ubuntu 10-20200416-0ubuntu1~18.04) 10.0.1 20200416 (experimental) [master revision 3c3f12e2a76:dcee354ce56:44b326839d864fc10c459916abcc97f35a9ac3de]
      • clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
      • clang version 11.0.0-++20200506091409+ca09dab303f-1~exp1~20200506072011.1666
  • Did you use a released version of the library or the version from the develop branch?

    • Version 3.7.3 from develop branch
  • unit tests compile and run successfully

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind: bugstate: stalethe issue has not been updated in a while and will be closed automatically soon unless it is updated

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions