[libcxx-commits] [libcxx] [libc++] Implement P2988R12: `std::optional<T&>` (PR #155202)

A. Jiang via libcxx-commits libcxx-commits at lists.llvm.org
Thu Oct 23 06:10:37 PDT 2025


================
@@ -0,0 +1,40 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+
+// <optional>
+
+#include <cassert>
+#include <optional>
+#include <type_traits>
+#include <utility>
+
+template <typename RefType, std::remove_reference_t<RefType> _Val>
+constexpr bool test() {
+  std::remove_reference_t<RefType> item{_Val};
+  std::optional<RefType> opt{item};
+
+  {
+    assert(*opt == item);
+    assert(&(*opt) == &item);
+  }
+  {
+    assert(*std::as_const(opt) == item);
+    assert(&(*std::as_const(opt)) == &item);
+  }
+
+  return true;
+}
+
+int main(int, char**) {
+  static_assert((test<int&, 1>()));
+  static_assert((test<double&, 1.0>()));
+  assert((test<int&, 1>()));
+  assert((test<double&, 1.0>()));
----------------
frederick-vs-ja wrote:

We can put the calls into a non-template `test` function and just write `static_assert(test()); test();` in `main`.

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


More information about the libcxx-commits mailing list