无法在枚举类模板参数的underlying_type上调用is_unsigned

Can't manage to call is_unsigned on the underlying_type of an enum class template parameter

提问人:GLJeff 提问时间:1/3/2023 最后编辑:Remy LebeauGLJeff 更新时间:1/3/2023 访问量:79

问:

我试图将此函数的使用限制为具有无符号基础类型(并作为枚举)的枚举类,但我一生都无法找出正确的语法。AddSubtract

template <class E>
concept EnumAddSubtract =
 std::is_enum_v<E> &&
 std::is_unsigned<std::underlying_type<E>::type> && //ERROR HERE
 requires() { {E::AddSubtract}; };

template <EnumAddSubtract E>
constexpr E operator+(E const & lhs, int const & rhs) {
    return static_cast<E>(static_cast<std::underlying_type<E>::type>(lhs) +
 static_cast<std::underlying_type<E>::type>(rhs));
}

我能够在其他情况下调用,例如:is_unsignedunderlying_type<>::type

enum class C : unsigned {};
std::cout << std::is_unsigned<std::underlying_type<C>::type>::value << '\n';
C++ 标准 C++20 枚举类

评论

1赞 yeputons 1/3/2023
请提供最小的完整示例(包括所有 s)和完整的编译器消息#include
3赞 yeputons 1/3/2023
a) 在 std::underlying_type<>::type 之前键入名称或使用 ;b) , 不是 ;c) 之后没有 parens 。underlying_type_tis_unsigned_vis_unsignedrequires
2赞 Remy Lebeau 1/3/2023
@yeputons应该作为答案而不是评论发布
0赞 alagner 1/3/2023
@yeputons b ;)我想依赖类型已经放宽了 C++20typename

答:

0赞 GLJeff 1/3/2023 #1

我需要接受is_unsigned的价值。使用 yeputons 的建议,使用以 _v 和 _t结尾的帮助程序函数变体,下面是编译的代码:

#include <iostream>
#include <type_traits>
 
template <class E>
concept EnumAddSubtract = std::is_enum_v<E> && std::is_unsigned_v<std::underlying_type_t<E>> && requires() { {E::AddSubtract}; };

template <EnumAddSubtract E>
constexpr E operator+(E const & lhs, int const & rhs) {
    return static_cast<E>(static_cast<std::underlying_type<E>::type>(lhs) + static_cast<std::underlying_type<E>::type>(rhs));
}

enum class C : unsigned {};
typedef std::underlying_type<C>::type tester;
 
int main() 
{
    std::cout << std::is_unsigned<std::underlying_type<C>::type>::value << '\n';
    std::cout << std::is_unsigned<tester>::value << '\n';
}

评论

0赞 Nicol Bolas 1/3/2023
"使用辅助函数 _v 和 _t“ 这些都不是”函数”。