portable.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2005-2009 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. // Force use of assert.
  5. #if defined(NDEBUG)
  6. #undef NDEBUG
  7. #endif
  8. #include <boost/container_hash/hash.hpp>
  9. #include <cassert>
  10. // This example illustrates how to customise boost::hash portably, so that
  11. // it'll work on both compilers that don't implement argument dependent lookup
  12. // and compilers that implement strict two-phase template instantiation.
  13. namespace foo
  14. {
  15. template <class T>
  16. class custom_type
  17. {
  18. T value;
  19. public:
  20. custom_type(T x) : value(x) {}
  21. std::size_t hash() const
  22. {
  23. boost::hash<T> hasher;
  24. return hasher(value);
  25. }
  26. };
  27. }
  28. #ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
  29. namespace boost
  30. #else
  31. namespace foo
  32. #endif
  33. {
  34. template <class T>
  35. std::size_t hash_value(foo::custom_type<T> x)
  36. {
  37. return x.hash();
  38. }
  39. }
  40. int main()
  41. {
  42. foo::custom_type<int> x(1), y(2), z(1);
  43. boost::hash<foo::custom_type<int> > hasher;
  44. assert(hasher(x) == hasher(x));
  45. assert(hasher(x) != hasher(y));
  46. assert(hasher(x) == hasher(z));
  47. return 0;
  48. }