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@lists.isocpp.org> on behalf of Rainer Deyke via Std-Proposals <std-proposals@lists.isocpp.org>
Sent: Thursday, July 16, 2026 11:22
To: std-proposals@lists.isocpp.org <std-proposals@lists.isocpp.org>
Cc: Rainer Deyke <rainerd@eldwood.com>
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@eldwood.com
--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals