是否可以手动为枚举类定义转换? [英] Is it possible to manually define a conversion for an enum class?

查看:73
本文介绍了是否可以手动为枚举类定义转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,您可以使用以下语法为一个类定义类型转换:

Normally you can define a cast for a class by using the following syntax:

class Test {
public:
  explicit operator bool() { return false; }
};

对于枚举类,有没有办法做到这一点? / code>?

Is there a way to do this or something similar for an enum class?

推荐答案

不,不是。

实际上,枚举类根本不是任何类。仅使用 class 关键字是因为突然将无范围的枚举更改为范围限定的枚举意味着重新制作 all 枚举代码。因此委员会决定,要区分新式枚举和旧式枚举,将使用 class 标记新枚举,因为它已经是一个关键字,因此没有枚举在C ++中可能被命名为 class 。他们本可以选择另一个,反正也没有多大意义。

Actually, an enum class is no class at all. The class keyword is only used because suddenly changing the unscoped enum to a scoped enum would have mean reworking all enums codes. So the committee decided that to distinguish between new-style and old-style enums, the new ones would be tagged with class, because it's a keyword already so no enum could have been named class in C++. They could have picked another, it would not have made much more sense anyway.

尽管有 class 关键字,它们仍然是常规枚举,因为方括号内仅允许枚举器(以及可能分配给它们的值)。

However, despite the class keyword they are still regular enums in that only enumerators (and potentially values assigned to them) are allowed within the brackets.

这篇关于是否可以手动为枚举类定义转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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