mirror of
https://github.com/nlohmann/json.git
synced 2026-03-24 01:42:46 +00:00
support types convertible to string_view as JSON keys (#4958)
Signed-off-by: khloodelhossiny <khloood.elhossiny@gmail.com> Co-authored-by: khloodelhossiny <khloood.elhossiny@gmail.com>
This commit is contained in:
@@ -1790,3 +1790,55 @@ TEST_CASE_TEMPLATE("element access 2 (additional value() tests)", Json, nlohmann
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
TEST_CASE("operator[] with user-defined std::string_view-convertible types")
|
||||
{
|
||||
using json = nlohmann::json;
|
||||
|
||||
class TestClass
|
||||
{
|
||||
std::string key_data_ = "foo";
|
||||
|
||||
public:
|
||||
operator std::string_view() const
|
||||
{
|
||||
return key_data_;
|
||||
}
|
||||
};
|
||||
|
||||
struct TestStruct
|
||||
{
|
||||
operator std::string_view() const
|
||||
{
|
||||
return "bar";
|
||||
}
|
||||
};
|
||||
|
||||
json j = {{"foo", "from_class"}, {"bar", "from_struct"}};
|
||||
TestClass foo_obj;
|
||||
TestStruct bar_obj;
|
||||
|
||||
SECTION("read access")
|
||||
{
|
||||
CHECK(j[foo_obj] == "from_class");
|
||||
CHECK(j[TestClass{}] == "from_class");
|
||||
CHECK(j[bar_obj] == "from_struct");
|
||||
CHECK(j[TestStruct{}] == "from_struct");
|
||||
}
|
||||
|
||||
SECTION("write access")
|
||||
{
|
||||
j[TestClass{}] = "updated_class";
|
||||
j[TestStruct{}] = "updated_struct";
|
||||
CHECK(j["foo"] == "updated_class");
|
||||
CHECK(j["bar"] == "updated_struct");
|
||||
|
||||
SECTION("direct std::string_view access")
|
||||
{
|
||||
CHECK(j[std::string_view{"foo"}] == "updated_class");
|
||||
CHECK(j[std::string_view{"bar"}] == "updated_struct");
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
Reference in New Issue
Block a user