C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Pre-proposal: Constraining accidental scalar append to std::basic_string

From: Qirong ZHANG <jiuwoyoubing_at_[hidden]>
Date: Mon, 18 May 2026 22:41:16 +0800
On Sun, May 17, 2026 at 9:26 PM Robin Savonen Söderholm via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> A better way to achieve the desired effect for CharT-only is to replace
the function with:
>
> std::string& operator+=(std::same_as<CharT> auto);
>
> This will only allow exactly 'CharT' and remove all other overloads.
>
> We could also add a
>
> [[deprecated("Potentially unexpected character conversion)
> std::string+=(/*not-same-as-but-convertible-to*/<CharT> auto); //same
> behaviour as before but with a deprecation warning.
>
> if we want to not immediately break things that rely on this but be able
to
> remove it in the future.
>
> // Robin

Thanks, this is a useful way to frame the mechanism.

I agree that replacing the single-code-unit operation with an exact-`CharT`
constrained overload is cleaner than only adding deleted poison-pill
overloads. Conceptually, the rule would be:

```cpp
template<class T>
  requires std::same_as<std::remove_cvref_t<T>, CharT>
basic_string& operator+=(T&&);
```

and similarly for `operator=` if the paper handles assignment and append
together.

That expresses the intended domain directly: single-code-unit
assignment/append accepts exactly `CharT`, not arbitrary values convertible
to `CharT`.

The deprecated fallback is also attractive as a transition mechanism:

```cpp
template<class T>
  requires (!std::same_as<std::remove_cvref_t<T>, CharT> &&
            std::convertible_to<T, CharT>)
[[deprecated("implicit conversion to basic_string::value_type is
deprecated")]]
basic_string& operator+=(T&&);
```

One concern is the interaction with expressions such as `s += 0`. If the
deprecated fallback is a better match than the C-string overload, then a
currently ill-formed or ambiguous expression might become well-formed with
a warning. That may or may not be acceptable, but it seems like something
the paper would need to call out explicitly.

So I think this suggests a useful design space for the next revision:

1. exact-`CharT` constrained `operator=` and `operator+=`;
2. deleted fallback for non-`CharT` but convertible-to-`CharT`;
3. deprecated fallback as a transition path;
4. tooling-only / clang-tidy as the first implementation step.

I also agree with keeping `push_back` out of scope. Its name already
denotes element insertion, so `getc` / `int_type`-style code has a clear
spelling there.

Thanks again.

--
Qirong Zhang

Received on 2026-05-18 14:41:27