Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum inside types - Compiler warning C4482 C++

I am using fully qualified name of the enum inside a method in one of my class. But I am getting compiler warning which says "warning C4482: nonstandard extension used: enum 'Foo' used in qualified name". In C++, do we need to use enums without the qualified name? But IMO, that looks ugly.

Any thoughts?

like image 856
Navaneeth K N Avatar asked Feb 05 '09 01:02

Navaneeth K N


3 Answers

Yes, enums don't create a new "namespace", the values in the enum are directly available in the surrounding scope. So you get:

enum sample {
  SAMPLE_ONE = 1,
  SAMPLE_TWO = 2
};

int main() {
  std::cout << "one = " << SAMPLE_ONE << std::endl;
  return 0;
}
like image 53
sth Avatar answered Nov 16 '22 14:11

sth


To make it clean, replace:

enum Fruit {

    ORANGE = 0,
    BANANA = 1

};

with

namespace Fruit {

    enum { //no enum name needed

        ORANGE = 0,
        BANANA = 1

    };

};

...

int f = Fruit::BANANA; //No warning
like image 41
Poy Avatar answered Nov 16 '22 13:11

Poy


While sth does answer the question, it didn't address how I've always used enums. Even though they're just more or less names for numbers, I've always used them to define types that can only have certain values.

If the enum is part of the class, then that helps consumers clearly identify an enum reference:

class Apple {
  enum Variety {
    Gala,
    GoldenDelicious,
    GrannySmith,
    Fuji
  }
  ...
};

Then consumers would be able declare instances of the enum, pass as parameters, and qualify them when referencing one of the types.

unsigned int GetCountOfApples( Apple::Variety appleVariety );
...
fujiCnt = GetCountOfApples( Apple::Fuji );

Sometimes you want an enum outside of a class or two enums in the same class, and you can do something like what Poy had. You won't be able to reference the enum type though, so just name it.

namespace Color {
  enum ColorEnum {
    Blue,
    Red,
    Black
  };

Now using the enum and values would work like:

Color::ColorEnum firstColor = Color::Blue;
Color::ColorEnum secondColor = Color::Red;

if( firstColor == secondColor )
....

Now if there happens to be different enums with the same name in them, they will always be qualified with what type they are. Then you could handle what gamblor is asking about.

BananaColorEnum banCol = BananaColor::Yellow;
TomatoColorEnum tomCol = TomatoColor::Yellow;
like image 15
jmc Avatar answered Nov 16 '22 14:11

jmc