Date: Thu, 16 Jul 2026 05:22:05 +0200
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?
> 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]
Received on 2026-07-16 03:22:11
