为什么`std :: byte`是枚举类而不是类? [英] Why is `std::byte` an enum class instead of a class?

查看:202
本文介绍了为什么`std :: byte`是枚举类而不是类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: byte 是一种抽象,应该提供从新标准17开始对C ++中的内存区域进行安全访问的类型。 ,则根据 http://en.cppreference.com/w/cpp/类型/字节

std::byte is an abstraction that is supposed to provide a type safe(r) access to regions of memory in C++, starting with the new standard 17. However, it's declared this way according to http://en.cppreference.com/w/cpp/types/byte:

enum class byte : unsigned char {} ;

也就是说,它是枚举类没有任何枚举。由于通常 enums 的目的是提供一组受限的枚举,所以这似乎有些奇怪。带有私有 unsigned char 成员的类似乎是更明显的方法。

That is, it is an enum class without any enumerations. Since usually the purpose of enums is to provide a restricted set of enumerations, this seems a bit strange. A class with a private unsigned char member seems like the more obvious way to do this.

为什么这样做

推荐答案

具有 class 标准不需要> unsigned char 成员与 unsigned char 相同的大小或对齐方式。标准要求枚举的大小和对齐方式与其基础类型相同。

A class with an unsigned char member would not be required by the standard to be the same size or alignment as unsigned char. Whereas the standard requires that enumerations be the same size and alignment as their underlying types.

现在,标准可以简单地声明它为 class 类型,没有标准定义的成员,但是对大小,对齐方式, constexpr 构造函数等有特定要求;实施必须遵循这些期望。但是,简单地使用 enum class 来获得相同的效果要容易得多。您将获得所需的所有构造函数和转换行为。并且由于 enum class 类型被视为不同于其基础类型的类型,因此您可以得到所需的所有行为,而没有用这种方式定义它的实际缺点。

Now, the standard could have simply declared that it is a class type with no standard-defined member, but with specific requirements on its size, alignment, constexpr constructors, etc; implementations would have to follow through on those expectations. But it's much easier to simply use enum class to get the same effect. You get all of the constructors and conversion behavior that you'd expect. And since enum class types are treated as different types than their underlying type, you get all of the behavior you want with no real downside to defining it this way.

这篇关于为什么`std :: byte`是枚举类而不是类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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