WileTheCoyot
WileTheCoyot

Reputation: 523

Implement c++ visitor pattern avoiding circular dependency

I'm implementing a visitor pattern in C++ has described here. I have this file structure:

Base.h
---------------
#ifndef BASE_H
#define BASE_H

#include "visitor.h"

class Base{
public: virtual void accept(const visitor& v)=0;
};

#endif

Derived.h
-----------------
#ifndef DERIVED_H
#define DERIVED_H

#include "base.h"
#include "visitor.h"

class Derived : Base {
public: virtual void accept(const visitor& v);
};

#endif

visitor.h
------------------
#ifndef VISITOR_H
#define VISITOR_H

#include "base.h"
#include "derived.h"

class visitor {
    void visit(const base& base);
    void visit(const derived& derived);
};

#endif

The cpp file only include the .h and define the acccept methods as described int the link above. The problem i have with these file structure is the circular dependency between headers. If i compile it with VS 2012 i get this error: Error C2504: Base class not defined. Thank you in advice and sorry for my bad english.

Edit: I have changed my code as as follow:

Base.h
---------------
#ifndef BASE_H
#define BASE_H

//#include "visitor.h"
class visitor;

class Base{
public: virtual void accept(const visitor& v)=0;
};

#endif

Derived.h
-----------------
#ifndef DERIVED_H
#define DERIVED_H

#include "base.h"
//#include "visitor.h"

class visitor;

class Derived : Base {
public: virtual void accept(const visitor& v);
};

#endif

visitor.h
------------------
#ifndef VISITOR_H
#define VISITOR_H

//#include "base.h"
//#include "derived.h"

class base;
class derived;

class visitor {
    void visit(const base& base);
    void visit(const derived& derived);
};

#endif

But now, on the cpp implementations (on base.cpp and derived.cpp) i get erorr c2872 'visitor' ambiguos symbol:

Base.cpp
---------
#include "base.h"
void base::accept(const visitor& v){ // on this line i get error c2872
   v.visit(this);
}

Derived.cpp
---------
#include "derived.h"
void derived::accept(const visitor& v){ // on this line i get error c2872
   v.visit(this);
}

Upvotes: 1

Views: 2971

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409356

In the visitor.h header file you don't need the includes, the compiler only need to know that the base and derived classes exists. This can easily be done by replacing the #include directives with the declarations of the classes:

class base;
class derived;

And in the other two header files you don't need the visitor.h include either, just replace that #include with

class visitor;

Upvotes: 10

Related Questions