diff --git a/README.md b/README.md index 953861f..86ff32c 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,9 @@ int main() std::cout << md["test"]["super"].to() << "\n"; cppdict::add("toto/tata/titi", 2.5, md); - std::cout << "at toto/tata/titi : " << md["toto"]["tata"]["titi"].to() << "\n"; + + double const d = md["toto"]["tata"]["titi"]; + std::cout << "at toto/tata/titi : " << d << "\n"; } ``` diff --git a/include/dict.hpp b/include/dict.hpp index 810f58f..aa95e6b 100644 --- a/include/dict.hpp +++ b/include/dict.hpp @@ -80,8 +80,8 @@ namespace // Visitor details std::visit( [key, lambdas...](auto&& value) { using T = std::decay_t; - if constexpr (NodeT::template is_value_v< - T> or !is_values_only_v) + if constexpr (NodeT::template is_value_v + or !is_values_only_v) make_visitor(lambdas...)(key, value); }, child_node->data); @@ -183,25 +183,13 @@ struct Dict } - bool isLeaf() const noexcept - { - return !isNode() && !isEmpty(); - } + bool isLeaf() const noexcept { return !isNode() && !isEmpty(); } - bool isNode() const noexcept - { - return std::holds_alternative(data); - } + bool isNode() const noexcept { return std::holds_alternative(data); } - bool isEmpty() const noexcept - { - return std::holds_alternative(data); - } + bool isEmpty() const noexcept { return std::holds_alternative(data); } - bool isValue() const noexcept - { - return !isNode() and !isEmpty(); - } + bool isValue() const noexcept { return !isNode() and !isEmpty(); } template()>> Dict& operator=(const T& value) @@ -240,6 +228,18 @@ struct Dict throw std::runtime_error("cppdict: not a map or not default"); } + template()>> + operator T&() const + { + return to(); + } + + template()>> + operator T&() + { + return to(); + } + bool contains(std::string const key) const noexcept { return isNode() and std::get(data).count(key); diff --git a/test/basic_dict_ops.cpp b/test/basic_dict_ops.cpp index 0160a48..2565c31 100644 --- a/test/basic_dict_ops.cpp +++ b/test/basic_dict_ops.cpp @@ -6,7 +6,7 @@ #include "dict.hpp" using Dict = cppdict::Dict; -TEST_CASE("Can (depp)copy nodes with operator=", "[simple cppdict::Dict]") +TEST_CASE("Can (deep)copy nodes with operator=", "[simple cppdict::Dict]") { Dict dict; dict["this"]["is"]["the"]["source"] = 3.14; @@ -14,6 +14,14 @@ TEST_CASE("Can (depp)copy nodes with operator=", "[simple cppdict::Dict() == 3.14); } +TEST_CASE("Can convert directly to type") +{ + Dict dict; + dict["this"]["is"]["the"]["source"] = 3.14; + double const pi = dict["this"]["is"]["the"]["source"]; + REQUIRE(pi == 3.14); +} + TEST_CASE("Can add values and retrieve them", "[simple cppdict::Dict]") { Dict dict;