Search code examples
c++classstaticnamespacesfriend

How can I use static members in friend functions without prefixing [class name]::


I have this code in Player.h

class Player {
  friend void clearBoard();

private:
  static char board[4][4][4];
};

and this code in Player.cpp

char Player::board[4][4][4] = {};

void
clearBoard() {
  for (byte i = 0; i < 4; i++)
    for (byte j = 0; j < 4; j++)
      for (byte k = 0; k < 4; k++)
        board[i][j][k] = ' ';
}

so during compilation I get an error

Player.cpp:37:9: error: ‘board’ was not declared in this scope
   37 |         board[i][j][k] = ' ';
      |         ^~~~~

I use board literally hundred other times in the Player.cpp and using Player:: with each one will negatively affect readability an my nerves.

Is there a way to escape this hell?

I have tried

  1. using Player::board;

  2. using Player::board[][][];

  3. Enclosing my class with namespace, then using that namespace.

without any effect.

All suggestions except

"just redefine clearBoard() as static"

will be greatly appreciated.


Solution

  • In general typing less is not a way to improve readability. Writing Player::board is good because if you write board outside of Player then it is not clear where it comes from. Having said this, you can always introduce an alias if a variable name is too long and you are too lazy to type its name repeadetely:

    void
    clearBoard() {
      auto& board = Player::board;
      for (byte i = 0; i < 4; i++)
        for (byte j = 0; j < 4; j++)
          for (byte k = 0; k < 4; k++)
            board[i][j][k] = ' ';
    }
    

    Just make sure to keep the scope of the alias short and in this specific example I fail to see the benefit (introducing the alias is more typing, not less).