From 71830be06d80b08a0a1eda8a34c063246c923792 Mon Sep 17 00:00:00 2001 From: chenguoping Date: Wed, 10 Jun 2020 19:27:28 +0800 Subject: [PATCH] fix issue#1275 --- include/nlohmann/json.hpp | 25 +++++++++++++++++++++++++ single_include/nlohmann/json.hpp | 25 +++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/include/nlohmann/json.hpp b/include/nlohmann/json.hpp index d1dc41192..0deb05833 100644 --- a/include/nlohmann/json.hpp +++ b/include/nlohmann/json.hpp @@ -3788,6 +3788,31 @@ class basic_json JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } + /*! + @brief overload for a default value of type rvalue + @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const + */ + template>::value + and not std::is_same::value, int>::type = 0> + detail::uncvref_t value(const typename object_t::key_type& key, ValueType && default_value) && + { + // only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if key is found, return value and given default value otherwise + const auto it = find(key); + if (it != end()) + { + return std::move(it->template get_ref()); + } + + return std::forward(default_value); + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); + } + /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index dd9b21c4f..9fd621c79 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -19566,6 +19566,31 @@ class basic_json JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } + /*! + @brief overload for a default value of type rvalue + @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const + */ + template>::value + and not std::is_same::value, int>::type = 0> + detail::uncvref_t value(const typename object_t::key_type& key, ValueType && default_value) && + { + // only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if key is found, return value and given default value otherwise + const auto it = find(key); + if (it != end()) + { + return std::move(it->template get_ref()); + } + + return std::forward(default_value); + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); + } + /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const