json icon indicating copy to clipboard operation
json copied to clipboard

Feature: Add constructor support for C++20 Ranges and Views

Open DanielHwangbo opened this issue 1 month ago • 2 comments

Description

This PR introduces a new constructor to basic_json that 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_json that 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:

auto view = nums | std::views::filter(...);
// Fails compilation or requires manual iterators:
json j(view.begin(), view.end());
auto view = nums | std::views::filter(...);
// Direct initialization supported:
json j(view);

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).

DanielHwangbo avatar Nov 30 '25 04:11 DanielHwangbo

🔴 Amalgamation check failed! 🔴

The source code has not been amalgamated. @DanielHwangbo Please read and follow the Contribution Guidelines.

github-actions[bot] avatar Nov 30 '25 09:11 github-actions[bot]

🔴 Amalgamation check failed! 🔴

The source code has not been amalgamated. @DanielHwangbo Please read and follow the Contribution Guidelines.

github-actions[bot] avatar Dec 08 '25 06:12 github-actions[bot]