enum.pass.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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
  10. // <functional>
  11. // make sure that we can hash enumeration values
  12. // Not very portable
  13. #include "test_macros.h"
  14. #include <functional>
  15. #include <cassert>
  16. #include <type_traits>
  17. #include <limits>
  18. enum class Colors { red, orange, yellow, green, blue, indigo, violet };
  19. enum class Cardinals { zero, one, two, three, five=5 };
  20. enum class LongColors : short { red, orange, yellow, green, blue, indigo, violet };
  21. enum class ShortColors : long { red, orange, yellow, green, blue, indigo, violet };
  22. enum class EightBitColors : uint8_t { red, orange, yellow, green, blue, indigo, violet };
  23. enum Fruits { apple, pear, grape, mango, cantaloupe };
  24. template <class T>
  25. void
  26. test()
  27. {
  28. typedef std::hash<T> H;
  29. static_assert((std::is_same<typename H::argument_type, T>::value), "" );
  30. static_assert((std::is_same<typename H::result_type, std::size_t>::value), "" );
  31. typedef typename std::underlying_type<T>::type under_type;
  32. H h1;
  33. std::hash<under_type> h2;
  34. for (int i = 0; i <= 5; ++i)
  35. {
  36. T t(static_cast<T> (i));
  37. const bool small = std::integral_constant<bool, sizeof(T) <= sizeof(std::size_t)>::value; // avoid compiler warnings
  38. if (small)
  39. assert(h1(t) == h2(static_cast<under_type>(i)));
  40. }
  41. }
  42. int main()
  43. {
  44. test<Cardinals>();
  45. test<Colors>();
  46. test<ShortColors>();
  47. test<LongColors>();
  48. test<EightBitColors>();
  49. test<Fruits>();
  50. }