Skip to content

Iterator doesn't satisfy std::incrementable because post-increment may change constness #3331

Closed
@falbrechtskirchinger

Description

@falbrechtskirchinger

The following code fails to compile:

nlohmann::json j = nlohmann::json::array({"1", "2", "3", "4"});
auto it = std::ranges::lower_bound(j, "2");

Here are the relevant excerpts from the compiler output with -fconcepts-diagnostics-depth=2:

error: no match for call to ‘(const std::ranges::__lower_bound_fn) (nlohmann::json&, const char [2])’
  388 |         auto it = std::ranges::lower_bound(j, "2");

iterator_concepts.h:611:10:   in requirements with ‘_Iter __i’ [with _Iter = nlohmann::detail::iter_impl<nlohmann::basic_json<...> >]
iterator_concepts.h:611:34: note: ‘(__i ++)’ does not satisfy return-type-requirement, because
  611 |       && requires(_Iter __i) { { __i++ } -> same_as<_Iter>; };

concepts:57:15:   required for the satisfaction of ‘__same_as<_Tp, _Up>’ [with _Tp = const nlohmann::detail::iter_impl<nlohmann::basic_json<...> >; _Up = nlohmann::detail::iter_impl<nlohmann::basic_json<...> >]
concepts:57:32: note: the expression ‘is_same_v<_Tp, _Up> [with _Tp = const nlohmann::detail::iter_impl<nlohmann::basic_json<...> >; _Up = nlohmann::detail::iter_impl<nlohmann::basic_json<...> >]’ evaluated to ‘false’

The compiler is telling us that the post-increment operator is adding const to the return type, which violates the requirements of the std::incrementable iterator concept.

Looking in json.hpp we find:

    /*!
    @brief post-increment (it++)
    @pre The iterator is initialized; i.e. `m_object != nullptr`.
    */
    iter_impl const operator++(int) // NOLINT(readability-const-return-type)
    {
        auto result = *this;
        ++(*this);
        return result;
    }

Remove const from the return type and the introductory code snippet compiles just fine.

Someone more familiar with the code base will have to decide whether that is an appropriate fix.

Which version of the library did you use?

  • latest release version 3.10.5
  • other release - please state the version: ___
  • the develop branch

Metadata

Metadata

Assignees

Labels

kind: bugsolution: proposed fixa fix for the issue has been proposed and waits for confirmation

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions