Why do people use enums in C++ as constants while

2019-01-16 16:19发布

Why do people use enums in C++ as constants when they can use const?

12条回答
Rolldiameter
2楼-- · 2019-01-16 16:39

enums also can be used as a type name. So you can define a function that takes an enum as a parameter, which makes it more clear what kinds of values should be given as arguments to the function, as compared to having the values defined as const variables and the function accepting just "int" as an argument.

Consider:

enum my_new_fangled_type {
  baz = 0,
  meh = 1
};

void foo (my_new_fangled_type bar) // bar can be a value listed in the enum
{
   ...
}

versus:

int const baz = 0;
int const meh = 1;

void foo (int bar) // what are valid values for bar?
{
   ...
}
查看更多
乱世女痞
3楼-- · 2019-01-16 16:46

There's a historical reason too when dealing with template metaprogramming. Some compilers could use values from an enum, but not a static const int to instantiate a class.

template <int N>
struct foo
{
    enum { Value = foo<N-1>::Value + N };
};

template <>
struct foo<0>
{
    enum { Value = 0; }
};

Now you can do it the more sensible way:

template <int N>
struct foo
{
    static const int Value = foo<N-1>::Value + N;
};

template <>
struct foo<0>
{
    static const int Value = 0;
};

Another possible reason, is that a static const int may have memory reserved for it at runtime, whereas an enum is never going to have an actual memory location reserved for it, and will be dealt at compile time. See this related question.

查看更多
forever°为你锁心
4楼-- · 2019-01-16 16:47

Using an enum documents the valid choices in a terse manner and allows the compiler to enforce them.

If they are using enum store global constants, like Pi, for example, then I don't know what their goal is.

查看更多
Evening l夕情丶
5楼-- · 2019-01-16 16:47

One reason is that const requires more typing:

enum { Val1, Val2, Val3 };

...versus...

const int Val1=0, Val2=1, Val3=2;
查看更多
ら.Afraid
6楼-- · 2019-01-16 16:48

Before compiler vendors implemented the ISO/IEC 14882:1998 C++ standard, this code to define a constant in a class scope resulted in a compile error:

class Foo {
    static const int MAX_LEN = 80;
    ...
};

If the constant is an integer type, a kludgy work around is define it in an enum inside the class:

class Foo {
    enum {
        MAX_LEN = 80
    };
    ...
};
查看更多
Rolldiameter
7楼-- · 2019-01-16 16:50

Enums are more descriptive when used. Consider:

int f(int fg, int bg)

versus

 int f(COLOR fg, COLOR bg)

In addition, enums give a bit more type-safety, because

  • integers are not implicitly convertible to enum types
  • enum of one type is not implicitly convertible to enum of another type
查看更多
登录 后发表回答