hash.pass.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 T> struct hash<optional<T>>;
  11. #include <optional>
  12. #include <string>
  13. #include <memory>
  14. #include <cassert>
  15. #include "poisoned_hash_helper.h"
  16. #include "test_macros.h"
  17. struct A {};
  18. struct B {};
  19. namespace std {
  20. template <>
  21. struct hash<B> {
  22. size_t operator()(B const&) TEST_NOEXCEPT_FALSE { return 0; }
  23. };
  24. }
  25. int main(int, char**)
  26. {
  27. using std::optional;
  28. const std::size_t nullopt_hash =
  29. std::hash<optional<double>>{}(optional<double>{});
  30. {
  31. optional<B> opt;
  32. ASSERT_NOT_NOEXCEPT(std::hash<optional<B>>()(opt));
  33. ASSERT_NOT_NOEXCEPT(std::hash<optional<const B>>()(opt));
  34. }
  35. {
  36. typedef int T;
  37. optional<T> opt;
  38. assert(std::hash<optional<T>>{}(opt) == nullopt_hash);
  39. opt = 2;
  40. assert(std::hash<optional<T>>{}(opt) == std::hash<T>{}(*opt));
  41. }
  42. {
  43. typedef std::string T;
  44. optional<T> opt;
  45. assert(std::hash<optional<T>>{}(opt) == nullopt_hash);
  46. opt = std::string("123");
  47. assert(std::hash<optional<T>>{}(opt) == std::hash<T>{}(*opt));
  48. }
  49. {
  50. typedef std::unique_ptr<int> T;
  51. optional<T> opt;
  52. assert(std::hash<optional<T>>{}(opt) == nullopt_hash);
  53. opt = std::unique_ptr<int>(new int(3));
  54. assert(std::hash<optional<T>>{}(opt) == std::hash<T>{}(*opt));
  55. }
  56. {
  57. test_hash_enabled_for_type<std::optional<int> >();
  58. test_hash_enabled_for_type<std::optional<int*> >();
  59. test_hash_enabled_for_type<std::optional<const int> >();
  60. test_hash_enabled_for_type<std::optional<int* const> >();
  61. test_hash_disabled_for_type<std::optional<A>>();
  62. test_hash_disabled_for_type<std::optional<const A>>();
  63. test_hash_enabled_for_type<std::optional<B>>();
  64. test_hash_enabled_for_type<std::optional<const B>>();
  65. }
  66. return 0;
  67. }