optional_U.pass.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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>
  11. // optional(optional<U>&& rhs);
  12. #include <optional>
  13. #include <type_traits>
  14. #include <memory>
  15. #include <cassert>
  16. #include "test_macros.h"
  17. using std::optional;
  18. template <class T, class U>
  19. void
  20. test(optional<U>&& rhs, bool is_going_to_throw = false)
  21. {
  22. bool rhs_engaged = static_cast<bool>(rhs);
  23. #ifndef TEST_HAS_NO_EXCEPTIONS
  24. try
  25. {
  26. optional<T> lhs = std::move(rhs);
  27. assert(is_going_to_throw == false);
  28. assert(static_cast<bool>(lhs) == rhs_engaged);
  29. }
  30. catch (int i)
  31. {
  32. assert(i == 6);
  33. }
  34. #else
  35. if (is_going_to_throw) return;
  36. optional<T> lhs = std::move(rhs);
  37. assert(static_cast<bool>(lhs) == rhs_engaged);
  38. #endif
  39. }
  40. class X
  41. {
  42. int i_;
  43. public:
  44. X(int i) : i_(i) {}
  45. X(X&& x) : i_(std::exchange(x.i_, 0)) {}
  46. ~X() {i_ = 0;}
  47. friend bool operator==(const X& x, const X& y) {return x.i_ == y.i_;}
  48. };
  49. int count = 0;
  50. struct Z
  51. {
  52. Z(int) { TEST_THROW(6); }
  53. };
  54. int main(int, char**)
  55. {
  56. {
  57. optional<short> rhs;
  58. test<int>(std::move(rhs));
  59. }
  60. {
  61. optional<short> rhs(short{3});
  62. test<int>(std::move(rhs));
  63. }
  64. {
  65. optional<int> rhs;
  66. test<X>(std::move(rhs));
  67. }
  68. {
  69. optional<int> rhs(3);
  70. test<X>(std::move(rhs));
  71. }
  72. {
  73. optional<int> rhs;
  74. test<Z>(std::move(rhs));
  75. }
  76. {
  77. optional<int> rhs(3);
  78. test<Z>(std::move(rhs), true);
  79. }
  80. static_assert(!(std::is_constructible<optional<X>, optional<Z>>::value), "");
  81. return 0;
  82. }