Skip to main content
Pigweed's logo Pigweed
  1. Home
  2. Reference
  3. C/C++
  4. pw::EnumTraits< T > Struct Template Reference
Loading...
Searching...
No Matches
pw::EnumTraits< T > Struct Template Reference

Overview

template<typename T>
struct pw::EnumTraits< T >

Compile-time metadata about an enum type.

The primary template is undefined. Specializations are generated automatically for enums registered with PW_ENUM.

Specializations provide the following members. Enumerators that share a value (aliases) are treated as a single distinct value.

  • enum_type — the enum type itself.
  • underlying_type — std::underlying_type_t<enum_type>.
  • kName — unqualified enum name, e.g. "MyEnum".
  • kFullyQualifiedName — fully qualified enum name, e.g. "::my::ns::MyEnum".
  • kTokenDomain — the pw_tokenizer domain the enum is tokenized in.
  • kDistinctValueCount — number of distinct values; equals kValues.size().
  • kIsContiguous — whether the distinct values cover every integer from kMin to kMax with no gaps.
  • kMin / kMax — smallest and largest enumerator values.
  • kValues — std::array<enum_type, kDistinctValueCount> of the distinct values in ascending order.
  • IsValid(value) — returns whether an enumerator or integer value is a valid enumerator; see pw::IsValidEnum.
Example
// A fixed-size array indexed by any contiguous PW_ENUM enum. Aliased
// enumerators share an entry, and enums that do not start at 0 are offset by
// kMin.
template <typename Enum, typename T>
class EnumArray {
public:
using Traits = pw::EnumTraits<Enum>;
static_assert(Traits::kIsContiguous, "EnumArray requires a contiguous enum");
constexpr T& operator[](Enum value) { return values_[Index(value)]; }
constexpr const T& operator[](Enum value) const {
return values_[Index(value)];
}
constexpr size_t size() const { return Traits::kDistinctValueCount; }
private:
static constexpr size_t Index(Enum value) {
return static_cast<size_t>(
static_cast<typename Traits::underlying_type>(value) -
static_cast<typename Traits::underlying_type>(Traits::kMin));
}
std::array<T, Traits::kDistinctValueCount> values_{};
};
Definition: traits.h:60
Source: pw_enum/examples/traits.cc
Warning
Do not specialize pw::EnumTraits by hand. Specializations are identified by an internal tag that only the code generator emits, so a hand-written one is not recognized by pw::has_enum_traits_v and is rejected by pw::IsValidEnum. To get traits for an enum, register it with PW_ENUM.

The documentation for this struct was generated from the following file: