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

前端 未结 12 1455
梦毁少年i
梦毁少年i 2020-12-08 02:28

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

12条回答
  •  被撕碎了的回忆
    2020-12-08 03:16

    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 
    struct foo
    {
        enum { Value = foo::Value + N };
    };
    
    template <>
    struct foo<0>
    {
        enum { Value = 0; }
    };
    

    Now you can do it the more sensible way:

    template 
    struct foo
    {
        static const int Value = foo::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.

提交回复
热议问题