optional_U.pass.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is dual licensed under the MIT and the University of Illinois Open
  6. // Source Licenses. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. // UNSUPPORTED: c++98, c++03, c++11, c++14
  10. // <optional>
  11. // template <class U>
  12. // optional(optional<U>&& rhs);
  13. #include <optional>
  14. #include <type_traits>
  15. #include <memory>
  16. #include <cassert>
  17. #include "test_macros.h"
  18. using std::optional;
  19. template <class T, class U>
  20. void
  21. test(optional<U>&& rhs, bool is_going_to_throw = false)
  22. {
  23. bool rhs_engaged = static_cast<bool>(rhs);
  24. #ifndef TEST_HAS_NO_EXCEPTIONS
  25. try
  26. {
  27. optional<T> lhs = std::move(rhs);
  28. assert(is_going_to_throw == false);
  29. assert(static_cast<bool>(lhs) == rhs_engaged);
  30. }
  31. catch (int i)
  32. {
  33. assert(i == 6);
  34. }
  35. #else
  36. if (is_going_to_throw) return;
  37. optional<T> lhs = std::move(rhs);
  38. assert(static_cast<bool>(lhs) == rhs_engaged);
  39. #endif
  40. }
  41. class X
  42. {
  43. int i_;
  44. public:
  45. X(int i) : i_(i) {}
  46. X(X&& x) : i_(std::exchange(x.i_, 0)) {}
  47. ~X() {i_ = 0;}
  48. friend bool operator==(const X& x, const X& y) {return x.i_ == y.i_;}
  49. };
  50. int count = 0;
  51. struct Z
  52. {
  53. Z(int) { TEST_THROW(6); }
  54. };
  55. int main()
  56. {
  57. {
  58. optional<short> rhs;
  59. test<int>(std::move(rhs));
  60. }
  61. {
  62. optional<short> rhs(short{3});
  63. test<int>(std::move(rhs));
  64. }
  65. {
  66. optional<int> rhs;
  67. test<X>(std::move(rhs));
  68. }
  69. {
  70. optional<int> rhs(3);
  71. test<X>(std::move(rhs));
  72. }
  73. {
  74. optional<int> rhs;
  75. test<Z>(std::move(rhs));
  76. }
  77. {
  78. optional<int> rhs(3);
  79. test<Z>(std::move(rhs), true);
  80. }
  81. static_assert(!(std::is_constructible<optional<X>, optional<Z>>::value), "");
  82. }