我有以下enum
:
enum enumLoanPaymentPolicy
{
Unspecified = 0,
InterestInArrears = 1 << 1,
InterestInAdvance = 1 << 2,
RoundUpRepayments = 1 << 3,
RoundInterest = 1 << 4,
RoundUpFlows = 1 << 5,
RoundingMask = RoundUpRepayments | RoundInterest | RoundUpFlows,
};
然后在其他地方,给定此枚举的值(foo
),我想提取与Round
相关的位集。
我使用foo & RoundingMask
,但我应该使用 type 吗?
理想情况下,我会使用somethingorother(enumLoanPaymentPolicy) bar = foo & RoundingMask
,其中somethingorother
有点像decltype
。这甚至可能吗?
答案 0 :(得分:6)
您正在寻找std::underlying_type
来自cppreference的示例代码:
#include <iostream> #include <type_traits> enum e1 {}; enum class e2: int {}; int main() { bool e1_type = std::is_same< unsigned ,typename std::underlying_type<e1>::type>::value; bool e2_type = std::is_same< int ,typename std::underlying_type<e2>::type>::value; std::cout << "underlying type for 'e1' is " << (e1_type?"unsigned":"non-unsigned") << '\n' << "underlying type for 'e2' is " << (e2_type?"int":"non-int") << '\n'; }