yohhoyの日記

技術的メモをしていきたい日記

is_scoped_enumメタ関数

C++11以降で導入されたscoped enumeration*1か否かを判別するメタ関数。本記事の内容はStack Overflowで見つけた質問と回答に基づく。

2020-11-14追記:C++2b(C++23)標準ライブラリに向けて提案文書(PDF)P1048R1が採択され、<type_traits>ヘッダにstd::is_scoped_enumメタ関数が追加される。Trip report: Autumn ISO C++ standards meeting (virtual) 参照。

#include <type_traits>

template<typename E>
struct is_scoped_enum : std::integral_constant<
  bool,
  std::is_enum<E>::value && !std::is_convertible<E, int>::value
> {};

scoped enumerationでは “int型への暗黙型変換” が提供されないことを利用している。N3337 7.2/p9より一部引用。

9 The value of an enumerator or an object of an unscoped enumeration type is converted to an integer by integral promotion (4.5). [Example: (snip)
Note that this implicit enum to int conversion is not provided for a scoped enumeration: (snip) -- end example]

関連URL

*1:enum class または enum struct で宣言する列挙型。C++03以前からの enum で宣言するunscoped enumerationとは区別される。