繁体   English   中英

是否可以在 C++ 的变量中保存多种类型的枚举?

[英]Is it possible to hold multiple types of enums in a variable in 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

我认为它可能只是一个 integer,但为了安全起见,还有其他方法可以做到这一点吗?

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

如果您可以忽略原始类型之间的区别,那么 integer 将起作用。 如果您想要更严格一点并且只允许对“兼容”枚举进行赋值和比较,那么可能需要一个用户定义的类型,该类型具有来自AB的隐式转换。 不幸的是,您不能直接在两个枚举之间添加转换,因为转换函数和转换构造函数都必须是成员函数,而枚举不允许。

如果您想稍后区分它们,那么boost::variant<A, B>会这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM