jeudi 2 septembre 2021

Use of scoped enum in a class prior to its definition

I'm trying to understand how the compiler handles this code. The two class methods both reference the enumeration before it is defined, but only one generates a compile error. I'm using GCC 9.2:

class Test {
  public:
    Test() {}
    ~Test(){}

    //gcc seems to be happy with this...
    int Foo()
    {
      TestState v = TestState::Value1;
      if (v == TestState::Value1) {
        return 0;
      } else if (v == TestState::Value2) {
        return 1;
      }
    }

    // ... but it doesn't work when used as a parameter
    int Bar(TestState v)
    {
      if (v == TestState::Value1) {
        return 0;
      } else if (v == TestState::Value2) {
        return 1;
      }
    }
  private:
    enum class TestState:bool
    {
      Value1 = false,
      Value2 = true
    };
};

In this case, the function Foo compiles fine under gcc 9.2, but Bar does not:

enum.cpp:18:13: error: ‘TestState’ has not been declared
     int Bar(TestState v)
             ^
enum.cpp: In member function ‘int Test::Bar(int)’:
enum.cpp:20:13: error: no match for ‘operator==’ (operand types are ‘int’ and ‘Test::TestState’)
       if (v == TestState::Value1) {
             ^
enum.cpp:22:20: error: no match for ‘operator==’ (operand types are ‘int’ and ‘Test::TestState’)
       } else if (v == TestState::Value2) {

Why does gcc seem to accept the usage of the enum prior to definition in one instance but not another? I understand it's not good practice to do this, but I'm still curious as to why it's the case.

Aucun commentaire:

Enregistrer un commentaire