C++ std::conditional_t 不会用 std::is_enum_v 和 std::underlying_type_t 编译

C++ std::conditional_t wont compile with std::is_enum_v and std::underlying_type_t

我正在尝试为可以索引到的类型编写类型特征,例如一个 std::vector,它应该包括枚举类型,因为我可以将它们转换为它们的基础类型。

到目前为止,我已经写了以下特征。

#include <iostream>
#include <type_traits>
#include <cinttypes>
#include <vector>
#include <utility>

template<typename T>
struct is_unsigned_integral :
    std::integral_constant<
        bool,
        std::is_integral<T>::value &&
        std::is_unsigned<T>::value
    > {};

template<typename T>
inline constexpr auto is_unsigned_integral_v = 
    is_unsigned_integral<T>::value;

template<typename, typename = void>
struct is_index : std::false_type {};

template<typename T>
struct is_index<
    T, 
    std::enable_if_t<
        is_unsigned_integral_v<
            std::conditional_t<
                std::is_enum_v<T>,
                std::underlying_type_t<T>,
                T
            >
        >
    >
> : std::true_type {};

template<typename T>
inline constexpr auto is_index_v = is_index<T>::value;

enum class idx : unsigned int {};

int main() {
    static_assert(is_index_v<unsigned int>, "");
    static_assert(is_index_v<idx>, "");
    
    return 0;
}

但是我收到以下错误消息

type_traits:2009:15: error: 
      only enumeration types have underlying types
      typedef __underlying_type(_Tp) type;

我希望得到以下结果

std::conditional_t<
    std::is_enum_v<T>,
    std::underlying_type_t<T>,
    T
>

将 eighter 计算为 T 或基础类型是 Tenum

我该怎么做?

替换失败,因为没有std::underlying_type_t<unsigned int>.

你可以单独专攻:

#include <iostream>
#include <type_traits>
#include <cinttypes>
#include <vector>
#include <utility>

template<typename T>
struct is_unsigned_integral :
    std::integral_constant<
        bool,
        std::is_integral<T>::value &&
        std::is_unsigned<T>::value
    > {};

template<typename T>
inline constexpr auto is_unsigned_integral_v = 
    is_unsigned_integral<T>::value;

template<typename, typename = void>
struct is_index : std::false_type {};

template<typename T>
struct is_index<
    T, 
    std::enable_if_t< is_unsigned_integral_v<T> >    
> : std::true_type {};

template <typename T>
struct is_index<T,std::enable_if_t<std::is_enum_v<T> >> : is_index<std::underlying_type_t<T> > {};


template<typename T>
inline constexpr auto is_index_v = is_index<T>::value;

enum class idx : unsigned int {};

int main() {
    static_assert(is_index_v<unsigned int>, "");
    static_assert(is_index_v<idx>, "");
    
    return 0;
}

PS: 来自 cppreference/std::underlying_type

If T is a complete enumeration (enum) type, provides a member typedef type that names the underlying type of T.

Otherwise, the behavior is undefined. (until C++20)

Otherwise, if T is not an enumeration type, there is no member type. Otherwise (T is an incomplete enumeration type), the program is ill-formed. (since C++20)

我不得不承认,我不确定在您的示例中未定义的行为(C++20 之前)如何与 SFINAE 一起使用。不过,请注意,这在上面不是问题,因为它仅在 T 实际上是枚举类型时才使用 std::underlying_type_t<T>