swap.pass.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. // <array>
  9. // template <class T, size_t N> void swap(array<T,N>& x, array<T,N>& y);
  10. #include <array>
  11. #include <cassert>
  12. #include "test_macros.h"
  13. // std::array is explicitly allowed to be initialized with A a = { init-list };.
  14. // Disable the missing braces warning for this reason.
  15. #include "disable_missing_braces_warning.h"
  16. struct NonSwappable {
  17. NonSwappable() {}
  18. private:
  19. NonSwappable(NonSwappable const&);
  20. NonSwappable& operator=(NonSwappable const&);
  21. };
  22. template <class Tp>
  23. decltype(swap(std::declval<Tp>(), std::declval<Tp>()))
  24. can_swap_imp(int);
  25. template <class Tp>
  26. std::false_type can_swap_imp(...);
  27. template <class Tp>
  28. struct can_swap : std::is_same<decltype(can_swap_imp<Tp>(0)), void> {};
  29. int main(int, char**)
  30. {
  31. {
  32. typedef double T;
  33. typedef std::array<T, 3> C;
  34. C c1 = {1, 2, 3.5};
  35. C c2 = {4, 5, 6.5};
  36. swap(c1, c2);
  37. assert(c1.size() == 3);
  38. assert(c1[0] == 4);
  39. assert(c1[1] == 5);
  40. assert(c1[2] == 6.5);
  41. assert(c2.size() == 3);
  42. assert(c2[0] == 1);
  43. assert(c2[1] == 2);
  44. assert(c2[2] == 3.5);
  45. }
  46. {
  47. typedef double T;
  48. typedef std::array<T, 0> C;
  49. C c1 = {};
  50. C c2 = {};
  51. swap(c1, c2);
  52. assert(c1.size() == 0);
  53. assert(c2.size() == 0);
  54. }
  55. {
  56. typedef NonSwappable T;
  57. typedef std::array<T, 0> C0;
  58. static_assert(can_swap<C0&>::value, "");
  59. C0 l = {};
  60. C0 r = {};
  61. swap(l, r);
  62. #if TEST_STD_VER >= 11
  63. static_assert(noexcept(swap(l, r)), "");
  64. #endif
  65. }
  66. #if TEST_STD_VER >= 11
  67. {
  68. // NonSwappable is still considered swappable in C++03 because there
  69. // is no access control SFINAE.
  70. typedef NonSwappable T;
  71. typedef std::array<T, 42> C1;
  72. static_assert(!can_swap<C1&>::value, "");
  73. }
  74. #endif
  75. return 0;
  76. }