Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions include/dict.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<node_t>(data); }
Expand Down
15 changes: 15 additions & 0 deletions test/basic_dict_ops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
#include <catch2/matchers/catch_matchers.hpp>

#include "dict.hpp"

#include <cstdint>
using Dict = cppdict::Dict<int, double, std::string>;

TEST_CASE("Can (deep)copy nodes with operator=", "[simple cppdict::Dict<int, double, std::string>]")
Expand Down Expand Up @@ -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, std::string>]")
{
// 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<std::int64_t, std::string> 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<std::string>() == "hello");
}
Loading