mirror of
https://github.com/aantron/better-enums.git
synced 2025-12-06 08:46:42 +08:00
Support using better-enum as key in dictionaries and maps (#77)
This enabled hashing so that unordered_map are supported.
This commit is contained in:
parent
8a0d376b53
commit
5a677ac72b
11
enum.h
11
enum.h
@ -1283,4 +1283,15 @@ BETTER_ENUMS_CONSTEXPR_ map<Enum, T> make_map(T (*f)(Enum))
|
||||
|
||||
}
|
||||
|
||||
#define BETTER_ENUMS_DECLARE_STD_HASH(type) \
|
||||
namespace std { \
|
||||
template <> struct hash<type> \
|
||||
{ \
|
||||
size_t operator()(const type &x) const \
|
||||
{ \
|
||||
return std::hash<size_t>()(x._to_integral()); \
|
||||
} \
|
||||
}; \
|
||||
}
|
||||
|
||||
#endif // #ifndef BETTER_ENUMS_ENUM_H
|
||||
|
||||
@ -31,7 +31,10 @@ BETTER_ENUM(Namespaced, short, One, Two)
|
||||
// be changed to be more precise in the future.
|
||||
#ifdef BETTER_ENUMS_HAVE_CONSTEXPR_
|
||||
|
||||
BETTER_ENUMS_DECLARE_STD_HASH(Channel)
|
||||
|
||||
#include <type_traits>
|
||||
#include <functional>
|
||||
|
||||
// Type properties.
|
||||
static_assert_1(std::is_class<Channel>());
|
||||
@ -161,6 +164,24 @@ static_assert_1(same_string(Depth::_names()[0], "HighColor"));
|
||||
|
||||
|
||||
// Run-time testing.
|
||||
class HashTests : public CxxTest::TestSuite {
|
||||
public:
|
||||
void test_same_values()
|
||||
{
|
||||
#ifdef _ENUM_HAVE_CONSTEXPR
|
||||
TS_ASSERT_EQUALS(
|
||||
std::hash<Channel>().operator()(Channel::Red),
|
||||
std::hash<int>().operator()(0));
|
||||
TS_ASSERT_EQUALS(
|
||||
std::hash<Channel>().operator()(Channel::Green),
|
||||
std::hash<int>().operator()(1));
|
||||
TS_ASSERT_EQUALS(
|
||||
std::hash<Channel>().operator()(Channel::Blue),
|
||||
std::hash<int>().operator()(2));
|
||||
#endif // #ifdef _ENUM_HAVE_CONSTEXPR
|
||||
}
|
||||
};
|
||||
|
||||
class EnumTests : public CxxTest::TestSuite {
|
||||
public:
|
||||
void test_constant_values()
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user