首页 > 解决方案 > 是否可以在 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++enums

解决方案


在 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;

推荐阅读