value_or.pass.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // UNSUPPORTED: c++98, c++03, c++11, c++14
  9. // <optional>
  10. // template <class U> constexpr T optional<T>::value_or(U&& v) &&;
  11. #include <optional>
  12. #include <type_traits>
  13. #include <cassert>
  14. #include "test_macros.h"
  15. using std::optional;
  16. using std::in_place_t;
  17. using std::in_place;
  18. struct Y
  19. {
  20. int i_;
  21. constexpr Y(int i) : i_(i) {}
  22. };
  23. struct X
  24. {
  25. int i_;
  26. constexpr X(int i) : i_(i) {}
  27. constexpr X(X&& x) : i_(x.i_) {x.i_ = 0;}
  28. constexpr X(const Y& y) : i_(y.i_) {}
  29. constexpr X(Y&& y) : i_(y.i_+1) {}
  30. friend constexpr bool operator==(const X& x, const X& y)
  31. {return x.i_ == y.i_;}
  32. };
  33. constexpr int test()
  34. {
  35. {
  36. optional<X> opt(in_place, 2);
  37. Y y(3);
  38. assert(std::move(opt).value_or(y) == 2);
  39. assert(*opt == 0);
  40. }
  41. {
  42. optional<X> opt(in_place, 2);
  43. assert(std::move(opt).value_or(Y(3)) == 2);
  44. assert(*opt == 0);
  45. }
  46. {
  47. optional<X> opt;
  48. Y y(3);
  49. assert(std::move(opt).value_or(y) == 3);
  50. assert(!opt);
  51. }
  52. {
  53. optional<X> opt;
  54. assert(std::move(opt).value_or(Y(3)) == 4);
  55. assert(!opt);
  56. }
  57. return 0;
  58. }
  59. int main(int, char**)
  60. {
  61. static_assert(test() == 0);
  62. return 0;
  63. }