1
0
mirror of https://github.com/nlohmann/json.git synced 2025-07-15 07:41:50 +03:00

re-adding const version operator[] (#135, #159)

It was a good idea to implement a const version of operator[] it in the
first place. I was a pity that this implementation was flawed. It was a
mistake to remove the const version completely. This commit
re-introduces the const version. My apologies for all the inconvenience.
This commit is contained in:
Niels
2015-12-21 08:42:42 +01:00
parent 9def0186be
commit 4351698c83
5 changed files with 197 additions and 2 deletions

View File

@ -2862,6 +2862,45 @@ class basic_json
}
}
/*!
@brief read-only access specified object element
Returns a const reference to the element at with specified key @a key. No
bounds checking is performed.
@warning If the element with key @a key does not exist, the behavior is
undefined.
@param[in] key key of the element to access
@return const reference to the element at key @a key
@throw std::domain_error if JSON is not an object
@complexity Logarithmic in the size of the container.
@liveexample{The example below shows how object elements can be read using
the [] operator.,operatorarray__key_type_const}
@sa @ref at(const typename object_t::key_type&) for access by reference
with range checking
@sa @ref value() for access by value with a default value
@since version 1.0
*/
const_reference operator[](const typename object_t::key_type& key) const
{
// [] only works for objects
if (is_object())
{
return m_value.object->find(key)->second;
}
else
{
throw std::domain_error("cannot use operator[] with " + type_name());
}
}
/*!
@brief access specified object element
@ -2911,6 +2950,48 @@ class basic_json
}
}
/*!
@brief read-only access specified object element
Returns a const reference to the element at with specified key @a key. No
bounds checking is performed.
@warning If the element with key @a key does not exist, the behavior is
undefined.
@note This function is required for compatibility reasons with Clang.
@param[in] key key of the element to access
@return const reference to the element at key @a key
@throw std::domain_error if JSON is not an object
@complexity Logarithmic in the size of the container.
@liveexample{The example below shows how object elements can be read using
the [] operator.,operatorarray__key_type_const}
@sa @ref at(const typename object_t::key_type&) for access by reference
with range checking
@sa @ref value() for access by value with a default value
@since version 1.0
*/
template<typename T, std::size_t n>
const_reference operator[](const T (&key)[n]) const
{
// at only works for objects
if (is_object())
{
return m_value.object->find(key)->second;
}
else
{
throw std::domain_error("cannot use operator[] with " + type_name());
}
}
/*!
@brief access specified object element with default value