SPH
ExtendedEnum.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include "common/Assert.h"
4 #include "common/Traits.h"
5 #include <limits>
6 
8 
9 template <typename TDerived, typename TBase>
10 struct IsExtended {
11  static constexpr bool value = false;
12 };
13 
14 #define SPH_EXTEND_ENUM(TDerived, TBase) \
15  template <> \
16  struct IsExtended<TDerived, TBase> { \
17  static constexpr bool value = true; \
18  }
19 
23 template <typename TBase>
24 class ExtendedEnum {
25 private:
26  using TValue = std::underlying_type_t<TBase>;
27  TValue value = 0;
28 
29 public:
30  using BaseType = TBase;
31 
32  ExtendedEnum() = default;
33 
35  ExtendedEnum(const TBase value)
36  : value(TValue(value)) {}
37 
39  template <typename TDerived, typename = std::enable_if_t<IsExtended<TDerived, TBase>::value>>
40  ExtendedEnum(const TDerived value)
41  : value(TValue(value)) {}
42 
44  operator TBase() const {
45  return TBase(value);
46  }
47 
49  template <typename TDerived, typename = std::enable_if_t<IsExtended<TDerived, TBase>::value>>
50  explicit operator TDerived() const {
51  return TDerived(value);
52  }
53 
54  bool operator<(const ExtendedEnum& other) const {
55  return value < other.value;
56  }
57 
58  bool operator==(const ExtendedEnum& other) const {
59  return value == other.value;
60  }
61 
62  bool operator==(const TBase& other) const {
63  return TBase(value) == other;
64  }
65 
66  template <typename TDerived, typename = std::enable_if_t<IsExtended<TDerived, TBase>::value>>
67  bool operator==(const TDerived& other) const {
68  return TDerived(value) == other;
69  }
70 
71  bool operator!=(const ExtendedEnum& other) const {
72  return value != other.value;
73  }
74 };
75 
76 template <typename T>
78  static constexpr bool value = false;
79 };
80 
81 template <typename TEnum>
82 struct IsExtendedEnum<ExtendedEnum<TEnum>> {
83  static constexpr bool value = true;
84 };
85 
Custom assertions.
NAMESPACE_SPH_BEGIN
Definition: BarnesHut.cpp:13
#define NAMESPACE_SPH_END
Definition: Object.h:12
Few non-standard type traits.
Helper type allowing to "derive" from enum class.
Definition: ExtendedEnum.h:24
ExtendedEnum(const TBase value)
Implicit constructor from base.
Definition: ExtendedEnum.h:35
bool operator==(const TDerived &other) const
Definition: ExtendedEnum.h:67
bool operator<(const ExtendedEnum &other) const
Definition: ExtendedEnum.h:54
TBase BaseType
Definition: ExtendedEnum.h:30
bool operator==(const ExtendedEnum &other) const
Definition: ExtendedEnum.h:58
bool operator!=(const ExtendedEnum &other) const
Definition: ExtendedEnum.h:71
ExtendedEnum()=default
ExtendedEnum(const TDerived value)
Implicit constructor from derived.
Definition: ExtendedEnum.h:40
bool operator==(const TBase &other) const
Definition: ExtendedEnum.h:62
static constexpr bool value
Definition: ExtendedEnum.h:78
static constexpr bool value
Definition: ExtendedEnum.h:11