2

Since c++ underlying type of c++ enum should be int.

However having code

enum class Properties{ first , second }
void tmp ( int i ) {}

tmp( Properties::first )

Compiler complains about Properties::first not being int rather Properties type.

Do i really have to cast it to int in order to pass value of enum to function or is there workaround?

Thanks for help.

Darlyn
  • 4,715
  • 12
  • 40
  • 90

2 Answers2

8

Properties is a scoped enumeration type. That's because you used the class keyword when defining it. Scoped enumerations are not implicitly convertible to their underlying type (or any integral type, for that matter). That's by design.

Just make it an unscoped enumeration if you want the converison:

enum Properties{ first , second };

There's also the compromise of using a namespace:

namespace Properties {
  enum { first , second };
}

That will give you the required access via fully qualified id, whilst retaining the implicit conversion.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
2

C++11 defines, the enum class (also called a scoped enumeration), which makes enumerations both strongly typed and strongly scoped. Here’s an example:

#include <iostream>
int main()
{
    enum class Color // "enum class" defines this as an scoped enumeration instead of a standard enumeration
    {
        RED, // RED is inside the scope of Color
        BLUE
    };

    enum class Fruit
    {
        BANANA, // BANANA is inside the scope of Fruit
        APPLE
    };

    Color color = Color::RED; // note: RED is not directly accessible any more, we have to use Color::RED
    Fruit fruit = Fruit::BANANA; // note: BANANA is not directly accessible any more, we have to use Fruit::BANANA

    if (color == fruit) // compile error here, as the compiler doesn't know how to compare different types Color and Fruit
        std::cout << "color and fruit are equal\n";
    else
        std::cout << "color and fruit are not equal\n";

    return 0;
}

scoped enumeration means :

enumerator names are local to the enum and also their values do not implicitly convert to other types.


In your case you have to use enum instead of enum calss to prevent that kind of error which is due to the scope of the enum.

Pouyan
  • 363
  • 5
  • 22