[libcxx-commits] [libcxx] [libc++] Implement P2988R12: `std::optional<T&>` (PR #155202)
A. Jiang via libcxx-commits
libcxx-commits at lists.llvm.org
Sun Nov 9 17:04:49 PST 2025
================
@@ -628,20 +634,87 @@ public:
using iterator = __wrap_iter<__pointer>;
using const_iterator = __wrap_iter<__const_pointer>;
# endif
+
+ // [optional.iterators], iterator support
+ _LIBCPP_HIDE_FROM_ABI constexpr iterator begin() noexcept {
+ auto& __derived_self = static_cast<optional<_Tp>&>(*this);
+ auto __ptr = [&__derived_self]() {
+ if constexpr (is_lvalue_reference_v<_Tp>) {
+ return __derived_self.has_value() ? std::addressof(__derived_self.__get()) : nullptr;
+ }
+ return std::addressof(__derived_self.__get());
+ }();
+
+# ifdef _LIBCPP_ABI_BOUNDED_ITERATORS_IN_OPTIONAL
+ return std::__make_bounded_iter(
+ std::__wrap_iter<__pointer>(__ptr),
+ std::__wrap_iter<__pointer>(__ptr),
+ std::__wrap_iter<__pointer>(__ptr) + (__derived_self.has_value() ? 1 : 0));
+# else
+ return iterator(__ptr);
+# endif
+ }
+
+ _LIBCPP_HIDE_FROM_ABI constexpr const_iterator begin() const noexcept {
+ auto& __derived_self = static_cast<const optional<_Tp>&>(*this);
+ auto* __ptr = [&__derived_self]() {
+ if constexpr (is_lvalue_reference_v<_Tp>) {
+ return __derived_self.has_value() ? std::addressof(__derived_self.__get()) : nullptr;
+ }
+ return std::addressof(__derived_self.__get());
+ }();
+
+# ifdef _LIBCPP_ABI_BOUNDED_ITERATORS_IN_OPTIONAL
+ return std::__make_bounded_iter(
+ std::__wrap_iter<__const_pointer>(__ptr),
+ std::__wrap_iter<__const_pointer>(__ptr),
+ std::__wrap_iter<__const_pointer>(__ptr) + (__derived_self.has_value() ? 1 : 0));
----------------
frederick-vs-ja wrote:
Ditto dropping (pre-existing) `std::`.
```suggestion
__wrap_iter<__const_pointer>(__ptr),
__wrap_iter<__const_pointer>(__ptr),
__wrap_iter<__const_pointer>(__ptr) + (__derived_self.has_value() ? 1 : 0));
```
https://github.com/llvm/llvm-project/pull/155202
More information about the libcxx-commits
mailing list