nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.97k stars 6.72k forks source link

inconsistency with string/string_view lookups #3912

Open Spongman opened 1 year ago

Spongman commented 1 year ago

Description

operator string_view() isn't used, whereas operator string() is.

Reproduction steps

https://godbolt.org/z/MYEYG3Gao

Expected vs. actual results

compiles

Minimal code example

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

using json = nlohmann::json;

struct Foo {
    operator std::string() const { return "foo"; }
};

struct Bar {
    operator std::string_view() const { return "bar"; }
};

int main() {

    json js {
        { "foo", "string" },
        { "bar", "string_view" },
    };

    std::cout << js[std::string{"foo"}] << "\n";
    std::cout << js[Foo{}] << "\n";

    std::cout << js[std::string_view{"bar"}] << "\n";
    std::cout << js[Bar{}] << "\n";
}

Error messages

<source>: In function 'int main()':
<source>:26:24: error: no match for 'operator[]' (operand types are 'json' {aka 'nlohmann::json_abi_v3_11_2::basic_json<>'} and 'Bar')
   26 |         std::cout << js[Bar{}] << "\n";
      |                        ^


### Compiler and operating system

linux gcc 12.2

### Library version

trunk

### Validation

- [x] The bug also occurs if the latest version from the [`develop`](https://github.com/nlohmann/json/tree/develop) branch is used.
- [ ] I can successfully [compile and run the unit tests](https://github.com/nlohmann/json#execute-unit-tests).