62 lines
1.3 KiB
Plaintext
Raw Normal View History

2025-01-12 20:37:50 +08:00
////
Copyright 2022 Peter Dimov
Distributed under the Boost Software License, Version 1.0.
https://www.boost.org/LICENSE_1_0.txt
////
[#describe]
= Hashing User Types with Boost.Describe
:idprefix: describe_
Let's look at our `point` class again:
[source]
----
class point
{
int x;
int y;
public:
point() : x(0), y(0) {}
point(int x, int y) : x(x), y(y) {}
};
----
If you're using {cpp}14 or above, a much easier way to add
support for `boost::hash` to `point` is by using
link:../../../describe/index.html[Boost.Describe] (and
get an automatic definition of `operator==` for free):
[source]
----
#include <boost/describe/class.hpp>
#include <boost/describe/operators.hpp>
class point
{
int x;
int y;
BOOST_DESCRIBE_CLASS(point, (), (), (), (x, y))
public:
point() : x(0), y(0) {}
point(int x, int y) : x(x), y(y) {}
};
using boost::describe::operators::operator==;
using boost::describe::operators::operator!=;
----
(Full code for this example is at
link:../../examples/point2.cpp[examples/point2.cpp].)
Since the `point` class has been annotated with `BOOST_DESCRIBE_CLASS`,
the library can enumerate its members (and base classes) and automatically
synthesize the appropriate `hash_value` overload for it, without us needing
to do so.