C ++ 17:仍使用枚举作为常量吗? [英] C++17: still using enums as constants?

查看:73
本文介绍了C ++ 17:仍使用枚举作为常量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯使用 enum 作为常量,它们写起来很快,可以放在.h文件中,并且工作正常。

 枚举{BOX_LEFT = 10,BOX_TOP = 50,BOX_WIDTH = 100,BOX_HEIGHT = 50}; 
枚举{REASONS_I_LIKE_ENUM_AS_CONSTANTS = 3};

这不再是个好主意吗?



我看到不错的原因偏爱枚举类(常规枚举隐式转换为int;常规枚举将其枚举数导出到周围的范围内),但这是在这种情况下偏爱旧枚举的原因。



我在 static constexpr int与老式的enum 更好,因为使用静态constexpr成员,您还必须在类外部声明它。但这显然在C ++ 17中不再适用,无论如何仅适用于类成员。



在c ++ 17中首选的方式是什么?

解决方案

这是主观的。



但是,这总是 枚举的滥用。您没有枚举任何东西;您只是在盗窃枚举功能来获取一些与任意整数值无关的东西,这些整数值不具有自己的逻辑类型。



这就是为什么枚举类在这里也不适用的原因(因为正如您所指出的,枚举类 强制应该存在的枚举的属性,而您实际上并不想这么做。) p>

由于静态constexpr int 不再存在任何问题,我会使用它(或 constexpr inline int ,或这周是什么)。


I am used to using enum as constants -- they're quick to write, can be placed in .h files, and work fine.

enum {BOX_LEFT=10, BOX_TOP=50, BOX_WIDTH=100, BOX_HEIGHT=50};
enum {REASONS_I_LIKE_ENUM_AS_CONSTANTS = 3};

Is this no longer a good idea?

I see good reasons to prefer enum class (conventional enums implicitly convert to int; conventional enums export their enumerators to the surrounding scope), but those are reasons to prefer old enum in this case.

I see in a thread on static constexpr int vs old-fashioned enum that old-style enum is better because with a static constexpr member you have to declare it outside the class as well. But this is apparently no longer true in C++17, and may only apply to class members anyway.

What's the preferred way in c++17?

解决方案

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).

这篇关于C ++ 17:仍使用枚举作为常量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆