Skip to content

Conversation

@DanielHwangbo
Copy link

@DanielHwangbo DanielHwangbo commented Nov 30, 2025

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

@github-actions
Copy link

🔴 Amalgamation check failed! 🔴

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

@github-actions github-actions bot added L and removed M labels Dec 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant