8

On this question, there's an answer that states:

You can use typedef to make Colour enumeration type accessible without specifying it's "full name".

typedef Sample::Colour Colour;
Colour c = Colour::BLUE;

That sounds correct to me, but someone down-voted it and left this comment:

Using the scope resolution operator :: on enums (as in "Colour::BLUE") is a compiler-specific extension, not standard C++

Is that true? I believe I've used that on both MSVC and GCC, though I'm not certain of it.

Community
  • 1
  • 1
Head Geek
  • 38,128
  • 22
  • 77
  • 87

5 Answers5

8

I tried the following code:

enum test
{
    t1, t2, t3
};

void main() 
{
    test t = test::t1;
}

Visual C++ 9 compiled it with the following warning:

warning C4482: nonstandard extension used: enum 'test' used in qualified name

Doesn't look like it's standard.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
  • Hm, you're right. Now that I think of it, what I've used was the equivalent of `Sample::BLUE`, not `Colour::BLUE`. Thanks. – Head Geek Jan 14 '09 at 02:14
  • 4
    Note: it's not standard for C++98. It's standard in C++11. – Nicol Bolas Mar 24 '12 at 17:48
  • @NicolBolas Yeah because now they recommend `enum class` in [C26812](https://learn.microsoft.com/en-us/cpp/code-quality/c26812?view=msvc-170) which _requires_ you to use scope resolution to use an `enum class` value – bobobobo Dec 11 '21 at 18:37
8

That is not standard.

In C++11, you will be able to make scoped enums with an enum class declaration.

With pre-C++11 compilers, to scope an enum, you will need to define the enum inside a struct or namespace.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • 4
    Note: In C++11, you can use scoping for non-`class` `enum`s too. You just don't *have* to scope them the way you do with `enum class`. – Nicol Bolas Mar 24 '12 at 17:49
5

This is not allowed in C++98. However, staring from C++11 you can optionally use scope resolution operator with "old-style" enums

enum E { A };

int main()
{
  A;    // OK
  E::A; // Also OK
}

Both ways of referring to A are correct in C++11 and later.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
4

In standard c++, things to the left of "::" must be a class or namespace, enums don't count.

Todd Gardner
  • 13,313
  • 39
  • 51
0

What you can do to get around it is to create a namespace that's the same name as the enumeration. That will effectively add the enumeration values into their own scope and you can use the name of the enumeration/namespace to refer to them. Of course it only works for enumerations that would otherwise exist in the global (or another namespace) scope.

There's also an article on this issue somewhere.

Dominik Grabiec
  • 10,315
  • 5
  • 39
  • 45