2

I need to use the enumerator of the enum class multiple times in one block of code and I would like to avoid the classical enum from C++03.

enum class Color {RED, GREEN};
{
    Color::RED //this works
    RED;       //how do I make this work (only for this block)?
}

I tried using

using namespace Color;

but it obviously did not work since Color is not a namespace.

Slazer
  • 4,750
  • 7
  • 33
  • 60

1 Answers1

4

This is impossible:

7.3.3p7 The using declaration [namespace.udecl] (n3337)

A using-declaration shall not name a scoped enumerator.

You can create a type alias using decltype:

using RED = decltype(red);

It does work in Clang, but is a reported bug.

The workaround is to use a variable.

Color red = Color::RED;

Rereading the question, it sounds like you want to bring all of the enum's variables into scope, not just one member. I suggest you read the proposal for enum class to see some of the issues it was trying to solve. The whole point of scoped enums is to avoid injecting its members into the enclosing scope.

So just use a regular enum.

user5378483
  • 457
  • 3
  • 5
  • Well thats a bit cumbersome. Moreover I cant use that in a switch statement like I wanted to. – Slazer Sep 26 '15 at 08:27
  • 1
    @Slazer You can make `red` constexpr. – user5378483 Sep 26 '15 at 08:39
  • I can not use regular enums, because i have two enums and both of them have one enumerator with the same name. I use one enum in one function and the other in another function. I want to use it because of type safety (2.1 in the proposal). I dont want any "color++" or "color=3" going on. – Slazer Sep 26 '15 at 08:50
  • @Slazer `color++` or `color=3` wouldn't work on a regular enum either. – user5378483 Sep 26 '15 at 08:59
  • I know but one can override that with -fpermissive, which one will do. In C++11 its a showstopper. This was just one reason though. The problem would not be solved with enums anyways as I said. – Slazer Sep 26 '15 at 09:02
  • @Slazer Hmm, `-fpermissive` doesn't allow it on either GCC or Clang. Perhaps you have an buggy compiler? Even then, it's not really good practice to allow non-conforming code to compile (especially if it's from the "permissive" option). I think the underlying issue is in how your program is written rather than the choice between enum and enum class. – user5378483 Sep 26 '15 at 09:05
  • It will make a warning from the error in MinGW 4.9.1. I can not use "enum" at all though. I have to use "enum class". I still do not see a solution to my problem. – Slazer Sep 26 '15 at 09:22