How to use typedef recursively?

Viewed 86

I want to write a program about courses a person can take each semester.I want to define a data type called CourseTable which is a vector of a struct called Course but in this struct I also have a "prerequisites" variable whose type I've decided to be CourseTable.

typedef vector<Course> CourseTable ;
struct Course
{
  ....
  CourseTable prerequisites;
};

I get compilation error in either order I put these two declarations.Do you have any suggestions what I should do?

2 Answers

Try placing an alias inside the structure:

struct Course {
    typedef std::vector<Course> CourseTable;
    CourseTable prerequisites;
};

However, more C++-ish solution would be to use using keyword for type aliases:

struct Course {
    using CourseTable = std::vector<Course>;
    CourseTable prerequisites;
};

or forward declare struct Course like:

struct Course;
using CourseTable = std::vector<Course>;

struct Course {
    CourseTable prerequisites;
};

You need to forward declare Course before typedef vector<Course> CourseTable;. That would look like

struct Course;
typedef vector<Course> CourseTable;
struct Course
{
    CourseTable prerequisites;
};
Related