• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 // Copyright 2005-2009 Daniel James.
3 // Distributed under the Boost Software License, Version 1.0. (See accompanying
4 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5 
6 // Force use of assert.
7 #if defined(NDEBUG)
8 #undef NDEBUG
9 #endif
10 
11 #include <boost/container_hash/hash.hpp>
12 #include <cassert>
13 
14 // This example illustrates how to customise boost::hash portably, so that
15 // it'll work on both compilers that don't implement argument dependent lookup
16 // and compilers that implement strict two-phase template instantiation.
17 
18 namespace foo
19 {
20     template <class T>
21     class custom_type
22     {
23         T value;
24     public:
custom_type(T x)25         custom_type(T x) : value(x) {}
26 
hash() const27         std::size_t hash() const
28         {
29             boost::hash<T> hasher;
30             return hasher(value);
31         }
32     };
33 }
34 
35 #ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
36 namespace boost
37 #else
38 namespace foo
39 #endif
40 {
41     template <class T>
hash_value(foo::custom_type<T> x)42     std::size_t hash_value(foo::custom_type<T> x)
43     {
44         return x.hash();
45     }
46 }
47 
main()48 int main()
49 {
50     foo::custom_type<int> x(1), y(2), z(1);
51 
52     boost::hash<foo::custom_type<int> > hasher;
53 
54     assert(hasher(x) == hasher(x));
55     assert(hasher(x) != hasher(y));
56     assert(hasher(x) == hasher(z));
57 
58     return 0;
59 }
60