c++ - 如何实现 is_enum_class 类型特征?

标签 c++ metaprogramming sfinae typetraits

<分区>

当且仅当传入的类型 T 是类枚举时,如何实现其值成员为 true 的类型特征?虽然我知道例如

+T{};

如果 T 是一个枚举会工作,如果它是一个枚举类则会失败,到目前为止我找不到将它用于 SFINAE 的方法。

最佳答案

基于您的 +T{} 测试:

选项#1:

尾随返回类型中的表达式 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>;

DEMO

选项#2:

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>;

DEMO 2

测试:

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/

相关文章:

c++ - shared_ptr 的 vector ,从函数返回并修改它

c++ - C++ 中的奇怪行为

c++ - 为 Firefox 辅助功能编译 .IDL 文件后出错

r - 查找包含 R 函数定义的源文件

Ruby:如何在程序中生成代码行?

c++ - 模板模板类谓词在部分特化中不起作用

c++ - SFINAE : Delete a function with the same prototype

c++ - Linux 下 C++ 中的 SSH 连接

c++ - 如何从成员函数模板类型签名中删除 const?

c++ - 为泛型类型重载函数与为给定类型及其子类型重载函数