variant_test_helpers.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // The LLVM Compiler Infrastructure
  5. //
  6. // This file is dual licensed under the MIT and the University of Illinois Open
  7. // Source Licenses. See LICENSE.TXT for details.
  8. //
  9. //===----------------------------------------------------------------------===//
  10. #ifndef SUPPORT_VARIANT_TEST_HELPERS_HPP
  11. #define SUPPORT_VARIANT_TEST_HELPERS_HPP
  12. #include <type_traits>
  13. #include <utility>
  14. #include <cassert>
  15. #include "test_macros.h"
  16. #if TEST_STD_VER <= 14
  17. #error This file requires C++17
  18. #endif
  19. // FIXME: Currently the variant<T&> tests are disabled using this macro.
  20. #define TEST_VARIANT_HAS_NO_REFERENCES
  21. #ifndef TEST_HAS_NO_EXCEPTIONS
  22. struct CopyThrows {
  23. CopyThrows() = default;
  24. CopyThrows(CopyThrows const&) { throw 42; }
  25. CopyThrows& operator=(CopyThrows const&) { throw 42; }
  26. };
  27. struct MoveThrows {
  28. static int alive;
  29. MoveThrows() { ++alive; }
  30. MoveThrows(MoveThrows const&) {++alive;}
  31. MoveThrows(MoveThrows&&) { throw 42; }
  32. MoveThrows& operator=(MoveThrows const&) { return *this; }
  33. MoveThrows& operator=(MoveThrows&&) { throw 42; }
  34. ~MoveThrows() { --alive; }
  35. };
  36. int MoveThrows::alive = 0;
  37. struct MakeEmptyT {
  38. static int alive;
  39. MakeEmptyT() { ++alive; }
  40. MakeEmptyT(MakeEmptyT const&) {
  41. ++alive;
  42. // Don't throw from the copy constructor since variant's assignment
  43. // operator performs a copy before committing to the assignment.
  44. }
  45. MakeEmptyT(MakeEmptyT &&) {
  46. throw 42;
  47. }
  48. MakeEmptyT& operator=(MakeEmptyT const&) {
  49. throw 42;
  50. }
  51. MakeEmptyT& operator=(MakeEmptyT&&) {
  52. throw 42;
  53. }
  54. ~MakeEmptyT() { --alive; }
  55. };
  56. static_assert(std::is_swappable_v<MakeEmptyT>, ""); // required for test
  57. int MakeEmptyT::alive = 0;
  58. template <class Variant>
  59. void makeEmpty(Variant& v) {
  60. Variant v2(std::in_place_type<MakeEmptyT>);
  61. try {
  62. v = v2;
  63. assert(false);
  64. } catch (...) {
  65. assert(v.valueless_by_exception());
  66. }
  67. }
  68. #endif // TEST_HAS_NO_EXCEPTIONS
  69. #endif // SUPPORT_VARIANT_TEST_HELPERS_HPP