Skip to content

inconsistency with string/string_view lookups #3912

@Spongman

Description

@Spongman

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).

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions