hash_variant_test.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2018 Daniel James
  2. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  3. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. #include "./config.hpp"
  5. #ifndef BOOST_HASH_TEST_STD_INCLUDES
  6. # include <boost/container_hash/hash.hpp>
  7. #endif
  8. #include <boost/config.hpp>
  9. #include <boost/core/lightweight_test.hpp>
  10. #if BOOST_HASH_HAS_VARIANT
  11. #include <variant>
  12. #include <string>
  13. void test_monostate()
  14. {
  15. std::monostate x1;
  16. std::monostate x2;
  17. boost::hash<std::monostate> hasher;
  18. BOOST_TEST(hasher(x1) == hasher(x2));
  19. }
  20. void test_variant_int()
  21. {
  22. std::variant<std::monostate, int> x1a;
  23. std::variant<std::monostate, int> x1b;
  24. std::variant<std::monostate, int> x2a(10);
  25. std::variant<std::monostate, int> x2b(x2a);
  26. std::variant<std::monostate, int> x3(20);
  27. boost::hash<std::variant<std::monostate, int> > hasher;
  28. BOOST_TEST(hasher(x1a) == hasher(x1a));
  29. BOOST_TEST(hasher(x1a) == hasher(x1b));
  30. BOOST_TEST(hasher(x1a) != hasher(x2a));
  31. BOOST_TEST(hasher(x1a) != hasher(x3));
  32. BOOST_TEST(hasher(x2a) == hasher(x2a));
  33. BOOST_TEST(hasher(x2b) == hasher(x2b));
  34. BOOST_TEST(hasher(x2a) != hasher(x3));
  35. BOOST_TEST(hasher(x3) == hasher(x3));
  36. }
  37. struct custom1 {
  38. int value;
  39. friend std::size_t hash_value(custom1 v) { return boost::hash_value(v.value); }
  40. };
  41. struct custom2 {
  42. int value;
  43. friend std::size_t hash_value(custom2 v) { return boost::hash_value(v.value); }
  44. };
  45. void test_variant_unique_types()
  46. {
  47. custom1 x11 = { 0 };
  48. custom1 x12 = { 1 };
  49. custom2 x21 = { 0 };
  50. custom2 x22 = { 1 };
  51. boost::hash<custom1> hasher1;
  52. boost::hash<custom2> hasher2;
  53. BOOST_TEST(hasher1(x11) == hasher2(x21));
  54. BOOST_TEST(hasher1(x11) != hasher2(x22));
  55. BOOST_TEST(hasher1(x12) != hasher2(x21));
  56. BOOST_TEST(hasher1(x12) == hasher2(x22));
  57. typedef std::variant<custom1, custom2> variant_type;
  58. variant_type y11(x11);
  59. variant_type y12(x12);
  60. variant_type y21(x21);
  61. variant_type y22(x22);
  62. boost::hash<variant_type> hasher;
  63. BOOST_TEST(hasher(y11) != hasher(y21));
  64. BOOST_TEST(hasher(y11) != hasher(y22));
  65. BOOST_TEST(hasher(y12) != hasher(y21));
  66. BOOST_TEST(hasher(y12) != hasher(y22));
  67. }
  68. #endif
  69. int main()
  70. {
  71. #if BOOST_HASH_HAS_VARIANT
  72. test_variant_int();
  73. test_variant_unique_types();
  74. #else
  75. BOOST_LIGHTWEIGHT_TEST_OSTREAM << "<variant> not available." << std::endl;
  76. #endif
  77. return boost::report_errors();
  78. }