C++17: still using enums as constants? [duplicate]

一个人想着一个人 提交于 2019-12-03 12:39:29

This is subjective.

However, this was always an abuse of enums. You're not enumerating anything; you're just stealing the enum feature to get some unrelated with arbitrary integer values which are not intended to have their own logical "type".

That's why enum class is not appropriate here either (because, as you pointed out, enum class enforces the properties of an enum that should be there but which you do not actually want).

Since there's no longer any problem with static constexpr int, I'd use that (or constexpr inline int, or whatever it is this week).

The example that you give for using enum's can be rewritten as:

struct Point
{
    int x;
    int y;
};

struct Box
{
    Point p;

    int width;
    int height;
};

constexpr Box b = { { 1, 2 }, 3, 4 };

int f()
{
    return b.p.x;
}

Using strong types instead of int could even be a benefit.

For me this is more legible. I could even add some functions into that.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!