为什么不能将int类型的枚举类值用作int [英] why can enum class values of type int not be used as int

查看:165
本文介绍了为什么不能将int类型的枚举类值用作int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于其自身的范围,我想将旧式的 enum 更改为 enum class:int .

I wanted to change an old-style enum to enum class : int because of its own scope.

但是编译器抱怨在整数算术中使用这些值.但是为什么-由于该枚举被显式地键入为int?

But the compiler complains about using the values in integer arithmetics. But why - since the enum is explicitly typed as int?

示例:

  enum class MsgType : int {
    Output = 1,
    Input  = 2,
    Debug  = 3
  };
  enum class MsgSender : int {
    A = 1,
    B = 2,
    C = 3
  };


  // later in code
  int id = (MsgType::Input << 16) + (MsgSender::A);

产生

错误C2678:二进制'<<':未找到采用'MyClass :: MsgType'类型的左操作数(或没有可接受的转换)的运算符

error C2678: binary '<<': no operator found which takes a left-hand operand of type 'MyClass::MsgType' (or there is no acceptable conversion)

这对我来说似乎有点不合逻辑.

This seems to be somewhat illogical to me.


我完全意识到抛弃他们的可能性.但是,如果我不希望它们可转换,为什么要将类型指定为 int .尤其是如果语法建议某种继承自 int "


I am totally aware of the possillity to cast them. But if I would not want them to be convertible, why would i specify the type to be int. Especially if the syntax suggest some kind of "inherited from int"

推荐答案

这就是功能.作用域枚举不能隐式转换为整数,因此您不能代替整数使用它们.它们是按设计强烈键入的.如果想要隐式转换,请使用无作用域枚举.

That's the feature. Scoped enumerations are not implicitly convertible to integers, so you can't use them in lieu of integers. They are strongly typed by design. If you want the implicit conversion, use unscoped enumerations.

enum MsgType : int {
  Output = 1,
  Input  = 2,
  Debug  = 3
};
enum MsgSender : int {
  A = 1,
  B = 2,
  C = 3
};

作用域和基础类型的规范是正交的.

Scoping and the specification of an underlying type are orthogonal.

或者,如果您只想定义一些操作,而枚举通常保持强类型,则可以重载适当的运算符以完成操作

Alternatively, if you only want some operations to be defined, while the enumerations remain strongly typed in general, you can overload the appropriate operators to accomplish that

int operator<<(MsgType, int); // etc

但是,如果我不希望它们可转换,为什么要指定类型为int

But if I would not want them to be convertible, why would i specify the type to be int

确保一定的布局.遵循特定的ABI.允许向前声明类型.

To ensure a certain layout. To follow a specific ABI. To allow forward declaring the type.

这篇关于为什么不能将int类型的枚举类值用作int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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