0

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

3
  • Do you need to later figure out which kind of enum e holds, or just the value? Commented May 29, 2020 at 18:11
  • Does the code you presented not work? Just use int instead of some_data_type Commented May 29, 2020 at 18:12
  • If not C++17 std::variant (or std::any), then in ONE variable will hard unless you wrap the "one variable" in a struct { enum { enum_A, enum_B } which; union { A a; B b; } value; } enum_value; Commented May 29, 2020 at 20:16

2 Answers 2

3

In C++17 and later, you can use std::variant for that:

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;
Sign up to request clarification or add additional context in comments.

Comments

1

If you're ok losing the distinction between the original types, then an integer would work. 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. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.