【问题标题】:Can you get the underlying type of an enum? [duplicate]你能得到一个枚举的底层类型吗? [复制]
【发布时间】:2016-01-29 00:20:50
【问题描述】:

我有以下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 &amp; RoundingMask,但是我应该使用什么type?

理想情况下,我会使用somethingorother(enumLoanPaymentPolicy) bar = foo &amp; RoundingMask,其中somethingorother 有点像decltype。这甚至可能吗?

【问题讨论】:

  • @LogicStuff 很好的发现。我的谷歌搜索没有出现。

标签: c++


【解决方案1】:

您正在寻找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';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 2021-09-20
    • 2014-08-02
    • 1970-01-01
    • 2020-01-04
    相关资源
    最近更新 更多