Home > Net >  Why aren't friend and declaration compatible when they are written exactly the same?
Why aren't friend and declaration compatible when they are written exactly the same?

Time:03-17

namespace CommonUtility
{
    Interface::CellType Foo(int);
}

// when placed as friend of class Interface
class Interface
{
public:
    static enum class CellType
    {
        Group,
        NoSuchType
    };
    friend Interface::CellType CommonUtility::Foo(int); // IDE warning not compatible to the declaration 
}

// definition
Interface::CellType CommonUtility::Foo(int i)
{
  if (i == 1)
   return Interface::CellType::Group;
  else
   return Interface::CellType::NoSuchType;
}

I don't understand why it gives a warning?

The definition and the friend declaration are both not compatible with the declaration in namespace CommonUtility, but I have typed them exactly the same.

CodePudding user response:

  1. For Interface::CellType Foo(int); the Interface::CellType is unknown at that point and should result in a compiler error.
  2. static enum class CellType would also result in a compiler error, because static is not correct here.

And finally:

The declaration of Interface::CellType CommonUtility::Foo(int); has to exists before friend Interface::CellType CommonUtility::Foo(int); can be used. But Interface::CellType Foo(int); can only be declared as soons as Interface::CellType is known. CellType is a nested type and cannot be forward decaled.

And these conditions conflict with each other.

You would need to move the whole enum class CellType {} outside of class Interface to get that working.

  •  Tags:  
  • c
  • Related