aboutsummaryrefslogtreecommitdiff
path: root/libcxx/test/std/utilities/optional/optional.iterator/begin.pass.cpp
blob: df95a8df3793fcc6337f93d045d9506f0aab6800 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//===----------------------------------------------------------------------===//
//
// 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>

// constexpr iterator optional::begin() noexcept;
// constexpr const_iterator optional::begin() const noexcept;

#include <cassert>
#include <iterator>
#include <optional>
#include <type_traits>
#include <utility>

template <typename T>
constexpr bool test() {
  std::optional<T> opt{T{}};

  { // begin() is marked noexcept
    static_assert(noexcept(opt.begin()));
    static_assert(noexcept(std::as_const(opt).begin()));
  }

  { // Dereferencing an iterator at the beginning == indexing the 0th element, and that calling begin() again return the same iterator.
    auto iter1 = opt.begin();
    auto iter2 = std::as_const(opt).begin();
    assert(*iter1 == iter1[0]);
    assert(*iter2 == iter2[0]);
    assert(iter1 == opt.begin());
    assert(iter2 == std::as_const(opt).begin());
  }

  { // Calling begin() multiple times on a disengaged optional returns the same iterator.
    std::optional<T> disengaged{std::nullopt};
    auto iter1 = disengaged.begin();
    auto iter2 = std::as_const(disengaged).begin();
    assert(iter1 == disengaged.begin());
    assert(iter2 == std::as_const(disengaged).begin());
  }

  return true;
}

constexpr bool tests() {
  assert(test<int>());
  assert(test<char>());
  assert(test<const int>());
  assert(test<const char>());
  return true;
}

int main(int, char**) {
  assert(tests());
  static_assert(tests());

  return 0;
}