From 104d4e2faf0241b5325716a026ebaeb116053139 Mon Sep 17 00:00:00 2001 From: Egor Bychin Date: Thu, 22 Aug 2024 00:50:13 +0400 Subject: [PATCH] Add `begin`/`end` --- include/tl/optional.hpp | 30 ++++++++++++++++++++++++++++++ tests/iterator.cpp | 22 ++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 tests/iterator.cpp diff --git a/include/tl/optional.hpp b/include/tl/optional.hpp index e9c59c2..546659c 100644 --- a/include/tl/optional.hpp +++ b/include/tl/optional.hpp @@ -1256,6 +1256,24 @@ class optional : private detail::optional_move_assign_base, swap(this->m_has_value, rhs.m_has_value); } + using iterator = T *; + using const_iterator = const T *; + + /// Returns an iterator to the stored value, otherwise returns a past-the-end + /// iterator + constexpr iterator begin() noexcept { + return std::addressof(this->m_value) + !has_value(); + } + constexpr iterator end() noexcept { + return std::addressof(this->m_value) + 1; + } + constexpr const_iterator begin() const noexcept { + return std::addressof(this->m_value) + !has_value(); + } + constexpr const_iterator end() const noexcept { + return std::addressof(this->m_value) + 1; + } + /// Returns a pointer to the stored value constexpr const T *operator->() const { return std::addressof(this->m_value); @@ -1992,6 +2010,18 @@ template class optional { void swap(optional &rhs) noexcept { std::swap(m_value, rhs.m_value); } + using iterator = T *; + using const_iterator = const T *; + + /// Returns an iterator to the stored value, otherwise returns a past-the-end + /// iterator + constexpr iterator begin() noexcept { return m_value + !has_value(); } + constexpr iterator end() noexcept { return m_value + 1; } + constexpr const_iterator begin() const noexcept { + return m_value + !has_value(); + } + constexpr const_iterator end() const noexcept { return m_value + 1; } + /// Returns a pointer to the stored value constexpr const T *operator->() const noexcept { return m_value; } diff --git a/tests/iterator.cpp b/tests/iterator.cpp new file mode 100644 index 0000000..2afd246 --- /dev/null +++ b/tests/iterator.cpp @@ -0,0 +1,22 @@ +#include +#include + +TEST_CASE("iterator reference", "[iterator.ref]") { + int val = 3; + + tl::optional o = val; + REQUIRE(o.begin() != o.end()); + REQUIRE(*o.begin() == 3); + + o = tl::nullopt; + REQUIRE(o.begin() == o.end()); +} + +TEST_CASE("iterator value constexpr", "[iterator.value.constexpr]") { + constexpr tl::optional empty; + STATIC_REQUIRE(empty.begin() == empty.end()); + + constexpr tl::optional value = 3; + STATIC_REQUIRE(value.begin() != value.end()); + STATIC_REQUIRE(*value.begin() == 3); +}