<分区>
当且仅当传入的类型 T 是类枚举时,如何实现其值成员为 true 的类型特征?虽然我知道例如
+T{};
如果 T 是一个枚举会工作,如果它是一个枚举类则会失败,到目前为止我找不到将它用于 SFINAE 的方法。
<分区>
当且仅当传入的类型 T 是类枚举时,如何实现其值成员为 true 的类型特征?虽然我知道例如
+T{};
如果 T 是一个枚举会工作,如果它是一个枚举类则会失败,到目前为止我找不到将它用于 SFINAE 的方法。
最佳答案
基于您的 +T{}
测试:
尾随返回类型中的表达式 SFINAE:
#include <type_traits>
template <typename T>
auto test(int) -> decltype((void)+T{}, std::false_type{});
template <typename T>
auto test(...) -> std::true_type;
template <typename T>
using is_enum_class = std::integral_constant<bool, decltype(test<T>(0))::value && std::is_enum<T>::value>;
在 void_t-fashion 中:
template <typename T, typename V = void>
struct test : std::false_type {};
template <typename T>
struct test<T, decltype((void)+T{})> : std::true_type {};
template <typename T>
using is_enum_class = std::integral_constant<bool, !test<T>::value && std::is_enum<T>::value>;
测试:
enum class EC { a, b };
enum E { c, d };
int main()
{
static_assert(is_enum_class<EC>::value, "!");
static_assert(!is_enum_class<E>::value, "!");
static_assert(!is_enum_class<int>::value, "!");
}
关于c++ - 如何实现 is_enum_class 类型特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936640/