如何实现is_enum_class类型特征? [英] How to implement is_enum_class type trait?

查看:88
本文介绍了如何实现is_enum_class类型特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can one implement type trait whose value member is true if and only if the passed in type T is a class enum? While I know that for instance

+T{};

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

will work if T is an enum and fail if it is an enum class, I couldn't find a way so far to use this for SFINAE.

推荐答案

基于您的+T{}测试:

尾随返回类型的表达SFINAE:

Expression SFINAE in trailing return type:

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

演示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, "!");
}

这篇关于如何实现is_enum_class类型特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆