Feature: Add constructor support for C++20 Ranges and Views #5018
+192
−133
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This PR introduces a new constructor to
basic_jsonthat enables direct initialization from C++20 Ranges and Views (e.g.,std::views::filter,std::views::transform).Motivation
Currently, attempting to initialize a JSON object from a C++20 view fails because the library does not natively recognize the view type as a container. Users are currently forced to manually pass iterators, which breaks the ergonomics of modern C++20 pipelines.
Feature: Add constructor support for C++20 Ranges and Views
Description
This PR introduces a new constructor to
basic_jsonthat enables direct initialization from C++20 Ranges and Views (e.g.,std::views::filter,std::views::transform).Motivation
Currently, attempting to initialize a JSON object from a C++20 view fails because the library does not natively recognize the view type as a container. Users are currently forced to manually pass iterators, which breaks the ergonomics of modern C++20 pipelines.
Before:
Implementation Details
I added a templated constructor that delegates to the existing (InputIT, InputIT) constructor.
SFINAE & Ambiguity Resolution: To prevent "ambiguous overload" errors (specifically with std::string and std::vector, which satisfy the Range concept but are already handled by the library), I added specific SFINAE guards. The new constructor is disabled via std::enable_if if:
The type is basic_json (preserves copy/move constructor priority).
The type is a json_ref.
The type is already a compatible_type (e.g., std::string), ensuring existing library behavior is preserved and no ambiguity errors occur during compilation.
Checklist
[x] The changes are described in detail, both the what and why.
[ ] If applicable, an existing issue is referenced.
[x] The source code is amalgamated by running make amalgamate.
[x] Verified that std::string initialization still works (no ambiguity).
[ ] The Code coverage remained at 100%. (A new test case may be required).