c++ - 检查枚举类是否包含特定标识符
问题描述
我在这里搜索了一下,很惊讶我没有找到任何类似的问题。很高兴任何提示,以防万一这已经得到回答。
我有一个定义了很多枚举类的代码库。其中一些指定了一个 totalNum 常量,例如
enum class Foo : int
{
a,
b,
c,
totalNum
}
其他人没有这个喜欢
enum class Bar : bool
{
oneOption,
otherOption
}
然后我有一个基本上像这样的功能
template <class EnumClassType>
EnumClassType typeToEnum (typename std::underlying_type<EnumClassType>::type value)
{
// If you hit this assertion, the value is outside of the valid enum range
assert (isPositiveAndBelow (value, decltype (value) (EnumClassType::totalNum)));
return EnumClassType (value);
}
虽然这对指定的枚举有效并且有意义,但totalNum
我想跳过这个断言,以防枚举中没有这样的标识符。有没有办法做到这一点?代码库目前使用 C++ 14,但由于即将发生编译器更改,也欢迎使用 C++ 17 解决方案。
解决方案
与此同时,使用评论中提到的@jfh 之类的方法自己找到了答案。
首先,这是一种检查枚举类是否包含具有特定名称的标识符的方法
template <class EnumToTest>
class EnumConstantDefined_totalNum
{
private:
using Yes = int8_t;
using No = int16_t;
template <class E>
static Yes test (decltype (E::totalNum)*);
template <class E>
static No test (...);
public:
static constexpr bool value = sizeof (test<EnumToTest> (0)) == sizeof (Yes);
};
然后我们可以使用 SFINAE 为这两种枚举指定两个重载。
template <class EnumType>
std::enable_if_t<EnumConstantDefined_totalNum<EnumType>::value, void> assertValueIsInRange (typename std::underlying_type<EnumType>::type value)
{
assert (isPositiveAndBelow (value, decltype (value) (EnumType::totalNum)));
}
template <class EnumType>
std::enable_if_t<! EnumConstantDefined_totalNum<EnumType>::value, void> assertValueIsInRange (typename std::underlying_type<EnumType>::type)
{
// do nothing
}
然后在实际的转换函数中使用这个断言函数
/**
Casts a value matching an enum class underlying type to an enum class constant and asserts that the
value is inside the valid enum range
*/
template <class EnumClassType>
EnumClassType typeToEnum (typename std::underlying_type<EnumClassType>::type value)
{
assertValueIsInRange<EnumClassType> (value);
return EnumClassType (value);
}
推荐阅读
- java - 嵌套ifs或ands?
- python - Python 多个子正则表达式
- algorithm - 停止后台服务的跨平台方案
- python - 为什么 numpy.save 为 sys.getsizeof 0.33MB 数据生成 100MB 文件?
- ffmpeg - 编码为 h264 无法使用 ffmpeg c api 发送一些帧
- reactjs - 如何使用 react-router 在组件中保存表单的状态
- python - 根据两个条件删除行
- angular - 以角度发布来自 API 的显示数据
- javascript - fetchAll 在 Javascript 中导致“无法读取属性”错误
- c - .c 文件中的静态函数/变量