5

I have an enum like this: (Actually, it's an enum class)

enum class truth_enum {
    my_true = 1,
    my_false = 0
};

I would like to be able to expose my_true to the global namespace, so that I can do this:

char a_flag = my_true;

Or at least:

char a_flag = (char)my_true;

Instead of this:

char a_flag = truth_enum::my_true;

Is this possible?

I have tried something like this:

typedef truth_enum::my_true _true_;

I receive the error: my_true in enum class truth_enum does not name a type

My guess is that my_true is a value not a type. Is there an alternative which I can do to enable this functionality in my programs?

Not ideal, but I could do something like:

enum class : const char { ... };
const char const_flag_false = truth_enum::my_false;
3
  • 1
    if you use enum class, you cannot avoid writing the prefix. verbosity is not a problem unless it hinders readability. Commented Jul 24, 2013 at 1:46
  • An enumerator of an enum class doesn't implicitly convert to an integer, so char a_flag = my_true; is wrong anyway. Commented Jul 24, 2013 at 1:46
  • I used a conversion above Commented Jul 24, 2013 at 1:49

2 Answers 2

1

Remove class from the enum definition. I'll assume that you are offended by implicit conversion to int. How about:

static constexpr truth_enum _true_ = truth_enum::my_true;
static constexpr truth_enum _false_ = truth_enum::my_false;

or simply

const truth_enum _true_ = truth_enum::my_true;
const truth_enum _false_ = truth_enum::my_false;
Sign up to request clarification or add additional context in comments.

8 Comments

Okay I will look into this one sec I need to fix my code while I remember
What does static contexpr do? Actually, what does contexpr do?
constepxrapplied to a variable makes it const and forces the compiler to compute its initializer at compile time. In this specific case, it's basically identical to const - I'm probably overusing the flashy new construct in places where it works but isn't really necessary.
okay I like that, but it is necessary? Once I removed the class keyword, it compiled absolutely fine. I can use my_true without doing truth_enum::my_true - should I be able to do this?
Apparently what I described above is the expected behaviours for an enum, but not an enum class.
|
0

Solution was easy, the mistake I made was to use enum class instead of enum.

Yeah, so still a bit confused actually - I can now just use the values like:

bool aboolean = (bool)my_true;

Instead of having to do this:

bool aboolean = (bool)truth_enum::my_true;

Why is this?

1 Comment

Enums in C++ inherit from C, where it's pretty much just a preprocessor macro. Thus, it is visible in the global namespace.

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.