[libcxx-commits] [libcxx] [libc++][string] P3044R2: sub-`string_view` from `string` (PR #147095)

Nikolas Klauser via libcxx-commits libcxx-commits at lists.llvm.org
Mon Sep 8 01:08:09 PDT 2025


================
@@ -0,0 +1,129 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// REQUIRES: std-at-least-c++26
+
+// <string>
+
+// constexpr basic_string_view<_CharT, _Traits> subview(size_type __pos = 0, size_type __n = npos) const;
+
+#include <cassert>
+#include <concepts>
+#include <string>
+#include <string_view>
+#include <utility>
+
+#include "constexpr_char_traits.h"
+#include "make_string.h"
+#include "min_allocator.h"
+#include "test_allocator.h"
+#include "test_macros.h"
+
+#define CS(S) MAKE_CSTRING(CharT, S)
+
+template <typename CharT, typename TraitsT, typename AllocT>
+constexpr void test() {
+  std::basic_string<CharT, TraitsT, AllocT> s{CS("Hello cruel world!"), AllocT{}};
+
+  { // With a default position and a character length.
+
+    // Also check if subview() is a const-qualified.
+    assert(std::as_const(s).subview() == CS("Hello cruel world!"));
+
+    // Check it the return type of subview() is correct.
+    std::same_as<std::basic_string_view<CharT, TraitsT>> decltype(auto) sv = s.subview();
+    assert(sv == CS("Hello cruel world!"));
+  }
+
+  { // Check with different position and length.
+
+    // With a explict position and a character length.
+    assert(s.subview(6, 5) == CS("cruel"));
+
+    // From the beginning of the string with a explicit character length.
+    assert(s.subview(0, 5) == CS("Hello"));
+
+    // To the end of string with the default character length.
+    assert(s.subview(12) == CS("world!"));
+
+    // From the beginning to the end of the string with explicit values.
+    assert(s.subview(0, s.size()) == CS("Hello cruel world!"));
+  }
+
+  // Test if exceptions are thrown correctly.
+#ifndef TEST_HAS_NO_EXCEPTIONS
+  if (!std::is_constant_evaluated()) {
+    { // With a position that is out of range.
+      try {
+        s.subview(s.size() + 1);
+        assert(false && "Expected std::out_of_range exception");
----------------
philnik777 wrote:

I'm not sure the explanation here is really necessary. This is a quite common pattern in the tests and I'm not sure anybody was ever confused why it exists.

https://github.com/llvm/llvm-project/pull/147095


More information about the libcxx-commits mailing list