diff --git a/include/dict.hpp b/include/dict.hpp index 5004987..7fa6fa3 100644 --- a/include/dict.hpp +++ b/include/dict.hpp @@ -158,6 +158,13 @@ struct Dict } + // exact match for string literals: with only operator[](std::string const&), `dict["key"]` + // is ambiguous with the built-in `"key"[dict]` when Dict implicitly converts to + // std::ptrdiff_t (a long / std::int64_t leaf) + Dict& operator[](const char* key) { return (*this)[std::string{key}]; } + Dict& operator[](const char* key) const { return (*this)[std::string{key}]; } + + bool isLeaf() const noexcept { return !isNode() && !isEmpty(); } bool isNode() const noexcept { return std::holds_alternative(data); } diff --git a/test/basic_dict_ops.cpp b/test/basic_dict_ops.cpp index 2565c31..80708e3 100644 --- a/test/basic_dict_ops.cpp +++ b/test/basic_dict_ops.cpp @@ -4,6 +4,8 @@ #include #include "dict.hpp" + +#include using Dict = cppdict::Dict; TEST_CASE("Can (deep)copy nodes with operator=", "[simple cppdict::Dict]") @@ -119,3 +121,16 @@ TEST_CASE("Can get_value key by delimiter if exists", "or default if missing") dict["this"]["is"]["pi"] = 3.14; REQUIRE(cppdict::get_value(dict, "this/is/e", 2.71) == 2.71); } + +TEST_CASE("String literal keys with a long leaf", "[cppdict::Dict]") +{ + // std::int64_t is std::ptrdiff_t on LP64, with the implicit operator T&() conversion + // `dict["key"]` must not be ambiguous with the built-in `"key"[dict]` + cppdict::Dict dict; + dict["first"] = std::int64_t{1} << 40; + dict["second"]["third"] = std::string{"hello"}; + auto const& cdict = dict; + std::int64_t const first = cdict["first"]; + REQUIRE(first == std::int64_t{1} << 40); + REQUIRE(cdict["second"]["third"].to() == "hello"); +}