C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Proposal: ranges::reserve

From: Yexuan Xiao <bizwen_at_[hidden]>
Date: Thu, 16 Jul 2026 08:24:01 +0000
I have realized that the second version I proposed is incorrect and the first version is correct, except for its name and the parameter.

________________________________
From: Std-Proposals <std-proposals-bounces_at_[hidden]> on behalf of Rainer Deyke via Std-Proposals <std-proposals_at_[hidden]>
Sent: Thursday, July 16, 2026 11:22
To: std-proposals_at_[hidden] <std-proposals_at_[hidden]>
Cc: Rainer Deyke <rainerd_at_[hidden]>
Subject: Re: [std-proposals] Proposal: ranges::reserve



On 7/15/26 22:21, Yexuan Xiao via Std-Proposals wrote:
> Sorry, I was writing it in the Mail app, so there were two mistakes. Naming it try_reserve might imply that the function can fail, but compared to reserve, it doesn't carry that implication, so I think reserve is a suitable name. I just came up with a new idea: if the container doesn't have a reserve function, then its size must be greater than or equal to n; otherwise, it's UB. This addresses the two concerns you had. Here is my revised implementation:
>
> template<class C>
> requires (!std::ranges::view<C>) && std::ranges::sized_range<C>
> constexpr void reserve(C &c, std::ranges::range_size_t<C> n)
> {
> if constexpr (requires { c.reserve(n); }) {
> c.reserve(n);
> } else {
> assert(n <= c.max_size());
> }
> }
>
> Alternatively, it could also throw bad_alloc, as inplace_vector's reserve does.

If it can't be used with non-vectors for n > c.max_size(), it shouldn't
be used with non-vectors at all. Here's a better version that catches
the error at compile time:

   template<class C> constexpr void reserve(
       C &c,
       std::ranges::range_size_t<C> n) {
     static_assert(requires { c.reserve(n); });
     c.reserve(n);
   }

Now, why would you want that if you can just call c.reserve(n) instead?


--
Rainer Deyke - rainerd_at_[hidden]
--
Std-Proposals mailing list
Std-Proposals_at_[hidden]
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2026-07-16 08:24:07