gpt4 book ai didi

c++ - 枚举与静态常量

转载 作者:IT老高 更新时间:2023-10-28 23:21:14 25 4
gpt4 key购买 nike

我目前正在考虑命名空间枚举或命名空间静态常量组是否更可取的问题。什么应该是默认选择,为什么?

选项 1:

namespace Direction
{
enum Direction
{
north,
east,
south,
west,
};
}

选项 2:

namespace Direction
{
static const unsigned char north = 0;
static const unsigned char east = 1;
static const unsigned char south = 2;
static const unsigned char west = 3;
}

两者各有优缺点。

专业枚举:

  1. 一些类型安全:

    void foo(Direction dir); // the compiler won't allow you to just pass an int or a value of an unrelated enum without explicitly casting it

反枚举:

  1. 类型安全相当有限:

    enum A
    {
    Entry1 = 1
    };

    enum B
    {
    Entry2 = 10
    };

    A a;
    if(a == Entry2)
    ; // ouch!
  2. 不支持除 int 之外的任何其他类型 - 在 C++ 11 之前,不能只拥有例如 long long、short 或 char 的枚举

  3. 枚举的命名空间不是最理想的

    1. 如果不将枚举封装到单独的命名空间中,那么它的所有成员都会污染周围的命名空间。

    2. 如果确实将枚举包装到一个单独的命名空间中,那么当使用枚举本身作为一种类型时会得到一些冗余:然后必须以 Direction::Direction 的方式声明一个方向变量(当不执行“使用 Direction::Direction”时,这将让他们再次污染外部命名空间(最后在代码的那部分,其中使用指令生效)),以便能够以 Direction::north 的方式命名其成员,而不仅仅是北

专业静态常量:

  1. 在 C++ 11 之前的 C++ 中提供更好的类型支持 - 例如,可以将 unsigned char 等类型用于常量
  2. 适当的范围界定 - 不污染外部命名空间,无需通过 using 指令明确要求(即使在有限范围内)

对比静态常量:

  1. 甚至比枚举更不安全——不能再像这样声明函数原型(prototype):

    void foo(Direction dir);

    但必须通过以下方式进行:

    void foo(unsigned char dir); // now each variable of type unsigned char or of a type that can implicitly be casted into unsigned char can be passed, even if its totally unrelated to the expected "enumeration" or if the value does not match the value of any of the expected consts

编辑:在这里,我发现了一篇关于枚举类型安全限制的有趣文章: http://www.drdobbs.com/enumerations/184401797

最佳答案

最大的区别在于打字。枚举具有不同的类型;静态 const 必须有一个现有的整数类型(尽管它可以在其他地方使用)。哪个更可取取决于你想要什么:在 Direction 的情况下,你可能想要一个独特的类型,枚举更可取。在其他情况下,什么你真正想要的是一个整数类型的命名常量,比如说作为数组的维度。在这些情况下, static const 是可能更可取。

关于c++ - 枚举与静态常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19865603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com