enum traitsの話

enum traits - std-proposals

enumの各種情報を取得する、enum_traitsを追加したらどうか、という話。

enumの最小値、最大値、要素数、文字列との変換等。

ファーストアイディアのインタフェース:

template <typename E>
struct enum_traits<E> {
  static_assert(is_enum<E>::value, "Only valid for enums!");
  
  typedef /* 基底の整数型 */ value_type;
  static constexpr const value_type min; // 最小値
  static constexpr const value_type max; // 最大値
  static constexpr const value_type ubound; // 最大値+1
  static constexpr const size_t count; // 要素数
  static constexpr const size_t distinct; // 独立してる値の数(?)
  static constexpr const bool is_contiguious; // 値が連続しているか
  static constexpr const bool is_regular; // 標準的な列挙型か(0から始まり値が連続している)
  static constexpr const bool has_zero; // 値として0を持っているか
  static constexpr const bool has_postive; // 1つ以上正の値を持っているか
  static constexpr const bool all_postive; // 全て正の値か
  static constexpr const bool has_negative; // 1つ以上負の値をもっているか
  static constexpr const bool all_negative; // 全て負の値か

  // 範囲for文用
  class iterator;
  class reverse_iterator;
  struct range;
  range<E> loop();
};

// enumをキーとする連想配列的なもの
template <typename E, typename T, typename CMP = std::equal_to>
class enum_table {
  …

  constexpr const T& operator[](E tag) const;
  constexpr bool lookup(const T& value, E& tag) const;
  constexpr bool lookup(T&& value, E& tag) const;
  constexpr size_t size() const;

  …
  constexpr iterator find(E tag);
  template <typename Comparable>
  constexpr iterator find(Comparable&& c); //lookup using CMP(const T&, C&&) or CMP(const T&, const C&) using perfect forwarding
  constexpr iterator find(T&& value); //lookup using CMP()
};

// 文字列との変換
template <typename E>
using enum_strtable = enum_table<E, const char*, [](const char* l, const char* r){ return strcmp(l, r) == 0; }>;