【发布时间】:2026-02-13 01:20:02
【问题描述】:
我收到了错误:
Error C2154 '_Ty': only enumeration type is allowed as an argument to compiler intrinsic type trait '__underlying_type'
我认为它不应该将底层类型解析为底层类型,因为我首先检查 T 是否为枚举。代码如下:
template <typename T>
struct Foo
{
static inline constexpr bool isArgIntegral = std::is_integral<T>::value;
static inline constexpr bool isArgEnum = std::is_enum_v<T>;
using integral_underlying_type = std::conditional<isArgEnum, std::underlying_type_t<T>, T>;
};
int main()
Foo<int> g; // only enumeration type is allowed as an argument to compiler intrinsic type trait '__underlying_type'
}
在调用 std::conditional 时,它不是首先检查条件(第一个参数),而是创建第二个和第三个参数的类,而不考虑条件,因此我为什么得到我不能用'int'调用underlying_type的错误?
如何获取 T 模板参数的整数类型,无论是整数还是枚举?
编辑:我的下一个尝试是将 typedef 放在 if constexpr 中:
if constexpr (std::is_enum_v<T>)
{
using integral_underlying_type = std::underlying_type_t<T>;
// Now std::underlying_type_t won't be called at all unless T is enum, right?
}
【问题讨论】:
-
std::conditional是一个模板——模板为任何实例化提供了一个单独的类型。但是为了能够确定实例化的类型,所有参数都需要被评估...... -
啊,有道理。
-
可能会感兴趣(尽管不要认为它是重复的):*.com/questions/44550976/how-stdconditional-works
-
在纸面上,如果您不使用
underlyong_type_t实用程序(因为它强制实例化),您可以解决它。延迟一步typename conditional_t<isArgEnum, underlying_type<T>, type_identity<T>>::type