c++ - 是否可以在 C++ 中的变量中保存多种类型的枚举?
问题描述
是否有可能在 C++ 中做这样的事情:
enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
eg1,
eg2,
eg3,
...
}
enum B {//Same structure as enum A
e1,
e2,
e3,
...
}
some_data_type e = eg1;//No errors here
e = e2;//No errors here
我认为它可能只是一个整数,但为了安全起见还有另一种方法吗?
解决方案
在 C++17 及更高版本中,您可以使用std::variant
:
enum A {//Starts from 0 and has no enum with out of place value like 0,1,5,40, etc.
eg1,
eg2,
eg3,
...
}
enum B {//Same structure as enum A
e1,
e2,
e3,
...
}
std::variant<A,B> e = eg1;
e = e2;
推荐阅读
- excel - 在 DAX 中传递变量
- c++ - 为什么在某些情况下我不需要“std::”?
- java - 在应用打开时手动更改时间后,Volley 未请求新请求
- mapbox-gl-js - 我可以配置 Mapbox GL JS 在没有 shift 键的情况下执行 dragRotate 行为吗?
- python-3.x - 通过 Python 运行命令提示符(或反之亦然)
- angular - 角度动画和惊人的显示:无
- java - Android外部数据库中的SQLite SELECT查询-表错误
- swift - 用于聊天应用通知系统的 Firestore、FCM 和 Cloud 功能
- python - PyOpenGl Pygame 窗口在运行时冻结
- c# - 输入 10 行 3 列的二维数组