【问题标题】:How to avoid error of narrowing conversion in c++11如何避免c++11中缩小转换的错误
【发布时间】:2021-07-20 05:45:14
【问题描述】:

我有下面的代码,它使用枚举值来初始化结构的向量。 我收到有关窄转换的错误。我已经推荐了微软文档:link 我可以通过以下代码解决问题。

#include <iostream>
#include <vector>
#include <string>

enum NUMBERS
{
    NUMBERS_ZERO    = 0xA0000000,
    NUMBERS_ONE     = 0xA0000001,
    NUMBERS_TWO     = 0xA0000002,
    NUMBERS_THREE   = 0xA0000003,
};

struct Person {
    uint32_t        m_id = 0;
    std::string     m_name;

    Person(uint32_t id, std::string name) :
        m_id(id), m_name(name) {}
};

std::vector<Person> PersonList =
{
    {static_cast<uint32_t>(NUMBERS_ZERO),   "abc"},
    {static_cast<uint32_t>(NUMBERS_ONE),    "pqr"},
    {static_cast<uint32_t>(NUMBERS_TWO),    "xyz"},
    {static_cast<uint32_t>(NUMBERS_THREE),  "zzz"}
};

int main()
{
    for (auto it : PersonList)
        std::cout << it.m_id << " : " << it.m_name << "\n";
    return 0;
}

因为我们可以看到上面带有类型转换的向量初始化看起来很奇怪/复杂。如何以更具可读性的方式改进代码。我已经尝试了下面的代码,但它会抛出 error: Conversion from 'Numbers' to 'uint32_t' requires a narrow conversion. 任何建议将不胜感激。

/*
struct Person {
    uint32_t        m_id = 0;
    std::string     m_name;

    Person(uint32_t id, std::string name) :
        m_id(static_cast<uint32_t>(id)), m_name(name) {}
};

std::vector<Person> PersonList =
{
    {NUMBERS_ZERO,  "abc"},
    {NUMBERS_ONE,   "pqr"},
    {NUMBERS_TWO,   "xyz"},
    {NUMBERS_THREE, "zzz"}
};
*/

【问题讨论】:

  • 对于这段代码 sn-p,我会删除 enum 并只定义这些值:const uint32_t NUMBERS_ZERO = 0xA0000000; 等。当然,在现实世界中,可能需要一个实际enum.

标签: c++ c++11 initializer-list


【解决方案1】:

您可以定义一个用于枚举的类型,这样就不需要强制转换了:

enum NUMBERS : uint32_t
{
    NUMBERS_ZERO    = 0xA0000000,
    NUMBERS_ONE     = 0xA0000001,
    NUMBERS_TWO     = 0xA0000002,
    NUMBERS_THREE   = 0xA0000003,
};

如果没有类型定义,则可以假定数字是有符号的并且不适合 32 位整数,因此使用了窄化转换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-09
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 2014-03-12
    • 2021-07-12
    相关资源
    最近更新 更多