std::underlying_type
与非枚举类型一起使用时调用未定义的行为。
但是未定义的行为出现在哪里?
在此代码中:
template<typename E>
constexpr std::enable_if_t<std::is_enum<E>::value, std::underlying_type_t<E>> IntEnum(E e)
{
return static_cast<std::underlying_type_t<E>>(e);
}
我尝试使用std::enable_if
防止用户调用IntEnum
与非枚举类型。但如enable_if
在决定是否可以调用该函数之前先评估它,它的模板参数也会评估,包括 std::underlying_type_t<E>
。那么如果用非枚举类型调用这个 UB 吗?我该如何更改它?
最佳答案
typename std::underlying_type<E>::type
即使对于非枚举类型也会进行评估(并且对 SFINAE 不友好)。
您可以使用一种间接方式来延迟评估并保持 SFINAE 友好:
template<typename E>
constexpr
typename std::enable_if_t<std::is_enum<E>::value, std::underlying_type<E>>::type
IntEnum(E e)
{
return static_cast<std::underlying_type_t<E>>(e);
}
关于c++ - std::underlying_type :SFINAE 是否可以防止未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746062/