简体   繁体   English

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

[英]Is it possible to hold multiple types of enums in a variable in C++?

Is it possible to do something like this 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

I think it could be something like just an integer, but just to be safe is there another way to do this?我认为它可能只是一个 integer,但为了安全起见,还有其他方法可以做到这一点吗?

In C++17 and later, you can use std::variant for that:在 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;

If you're ok losing the distinction between the original types, then an integer would work.如果您可以忽略原始类型之间的区别,那么 integer 将起作用。 If you want to be a little more restrictive and only allow assignment from and comparison against "compatible" enums, then a user-defined type with implicit conversion from both A and B is probably wanted.如果您想要更严格一点并且只允许对“兼容”枚举进行赋值和比较,那么可能需要一个用户定义的类型,该类型具有来自AB的隐式转换。 Unfortunately you can't add conversions directly between two enums because conversion functions and converting constructors both have to be member functions, which enums don't allow.不幸的是,您不能直接在两个枚举之间添加转换,因为转换函数和转换构造函数都必须是成员函数,而枚举不允许。

If you want to keep them distinguished later, then boost::variant<A, B> will do that.如果您想稍后区分它们,那么boost::variant<A, B>会这样做。

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

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