Improve error message for const fields (#2818)

* Improve error message for const fields

* Reject const arguments to get_to() with a clear message

Reword the static_assert, add it to the C array overload of get_to() as well,
and document that v must not be const.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

---------

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
Co-authored-by: Niels Lohmann <mail@nlohmann.me>
This commit is contained in:
Alexander Lanin
2026-09-25 18:02:38 +02:00
committed by GitHub
parent 02dd3e67f2
commit 465407f3ce
3 changed files with 9 additions and 0 deletions

View File

@@ -21,6 +21,10 @@ This overload is chosen if:
- `ValueType` is not `basic_json`,
- `json_serializer<ValueType>` has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`
`v` must not be `const`. Passing a `const` object is a compile-time error. For types such as arithmetic types, enums,
and C arrays, the error is a `static_assert` that names the problem. For other types, the overload is not viable, and
the compiler reports that no matching `get_to` was found.
## Template parameters
`ValueType`
@@ -67,3 +71,4 @@ Depends on the `json_serializer<ValueType>::from_json()` implementation.
## Version history
- Since version 3.3.0.
- Added a `static_assert` with a clear message for `const` arguments in version 3.13.0.

View File

@@ -2553,6 +2553,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
ValueType & get_to(ValueType& v) const noexcept(noexcept(
JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
{
static_assert(!std::is_const<ValueType>::value, "get_to() cannot deserialize into a const value");
JSONSerializer<ValueType>::from_json(*this, v);
return v;
}
@@ -2578,6 +2579,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
noexcept(noexcept(JSONSerializer<Array>::from_json(
std::declval<const basic_json_t&>(), v)))
{
static_assert(!std::is_const<T>::value, "get_to() cannot deserialize into a const value");
JSONSerializer<Array>::from_json(*this, v);
return v;
}

View File

@@ -27198,6 +27198,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
ValueType & get_to(ValueType& v) const noexcept(noexcept(
JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
{
static_assert(!std::is_const<ValueType>::value, "get_to() cannot deserialize into a const value");
JSONSerializer<ValueType>::from_json(*this, v);
return v;
}
@@ -27223,6 +27224,7 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
noexcept(noexcept(JSONSerializer<Array>::from_json(
std::declval<const basic_json_t&>(), v)))
{
static_assert(!std::is_const<T>::value, "get_to() cannot deserialize into a const value");
JSONSerializer<Array>::from_json(*this, v);
return v;
}