HiroIshida
HiroIshida

Reputation: 1603

c++: how to define function that accpets all the sub-class of a speciic class

Let me write the relation that A is a sub-class of B by A < B. Suppose there is a relation A < B < C between three classes.

Now, what I want to do is to define a function/class-method that can take argument of all A, B and C (all the sub-class of A). Is it possible? and if so, how can I do this?

EDIT: MOTIVATION The motivation of this is as follows: Let say I want to solve a maze. The solver function solve_maze takes a Maze and solve the maze. By default, is_obstacle_free is set to return true always. This means that default maze is the empty space.

What I want to do is, enabling the user to define their custom CustomMaze by inheriting the Maze class if they want. User can change the shape of the maze by tweaking the is_obstacle_free function. Maybe, another user want to define class CustomMaze2 inheriting from CustomMaze.

If I can define solve_maze function that accept any sub-type of Maze, we can avoid defining solve_maze anytime users added a new maze type.

class Maze
{
   virtual bool is_obstacle_free(Point p){
       return true;
   }
};

class CustomMaze : public Maze
{
  bool is_obstacle_free(Point p) override;
};

void solve_maze(Space s, Solution& sol){
   \\ call a lot of is_obstacle_free inside
}

Upvotes: 0

Views: 88

Answers (1)

erenon
erenon

Reputation: 19118

void sample(A& a);

will accept anything that derives from A, but sample will only use a as if it were an A object (without casting).

With templates, you can do this without casting:

template <typename T>
void sample(T& t)
{
  static_assert(std::is_base_of<A,T>::value, "T must be derived from A");
  // T is whatever sample was called with.
}

Upvotes: 1

Related Questions