Why should I prefer static constexpr int in a class over enum for class-level integral constants?

后端 未结 3 1301
我寻月下人不归
我寻月下人不归 2021-02-14 08:18

C++17 Update: static constexpr variables are implicitly inline so there\'s no external definition necessary.


Original qu

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-14 08:49

    The reason I would give you is that using enum { } for constants is a misuse of the term enum. You're not enumerating anything. It's a common misuse, granted; it has its practical advantages; but it's just kind of wrong. There should be a way to say "this is just a compile-time constant and nothing else". constexpr isn't that thing either, but it's closer than enum. And it's rightly the case that you can't enum floating-point values.

    That being said - I often use enums for constants myself, when I want to protect myself against people writing something like void* ptr = &some_constant_value; std::cout << ptr;

提交回复
热议问题