samedi 1 mai 2021

How to deal with "not covariant" errors in paired hierarchies (C++)

Suppose I want a class Team to have a virtual get_player member which is implemented by FootballTeam and RugbyTeam, and that these implementations return the covariant types FootballPlayer and RugbyPlayer.

Suppose I also want Player to have a virtual get_team member which is implemented by FootballPlayer and RugbyPlayer, and that these implementations return the covariant types FootballTeam and RugbyTeam.

Is it possible to implement this pattern? I've tried, but, when overriding the get_player member of Team, I'm getting the error: "Return type of virtual function 'get_player' is not covariant with the return type of the function it overrides".

I can't define the Player hierarchy first, because then I'd have the same problem but the other way around!

class Player;
class FootballPlayer;
class RugbyPlayer;

class Team {
  virtual Player &get_player() = 0;
};
class FootballTeam : public Team {
  FootballPlayer &get_player() override; // error here
};
class RugbyTeam : public Team {
  RugbyPlayer &get_player() override; // error here
};

class Player {
  virtual Team& get_team() = 0;
};
class FootballPlayer : public Player {
  FootballTeam& get_team() override;
};
class RugbyPlayer : public Player {
  RugbyTeam& get_team() override;
};

Aucun commentaire:

Enregistrer un commentaire