I’m having the following class setup (here only with relevant content):
// Message.h
class Message { };
typedef std::shared_ptr<Message> MessagePtr;
// Task.h
#include "Message.h"
/*
* On include of Communication.h compilation fails.
*/
class Task {
public:
send(const MessagePtr &msg) {
// Call to Communication::send
}
MessagePtr recv() {
// Call to Communication::recv
}
};
typedef std::shared_ptr<Task> TaskPtr;
// Base.h
#include "Task.h"
class Base {
std::map<TaskPtr, std::vector<TaskPtr>> taskMap;
};
// Runtime.h
#include "Base.h"
class Runtime : public Base { };
// Communication.h
#include "Base.h"
class Message; // Forward declaration
class Communication : public Base {
public:
void send(const TaskPtr &caller, const MessagePtr &msg);
MessagePtr recv(const TaskPtr &caller);
};
My goal is to provide kind of an independent communication layer within Communication to let tasks communicate with each other. The receiver list is defined within taskMap (kind of publish-subscribe where the sender does not know the receivers).
For this purpose my idea is to use a callback function (e.g. with std::bind or similar) from Task to Communication. However, I’m not able to implement this, since whenever I include the Communication Header within Task compilation fails, which is, due to circular includes.
So I’m not sure about how to forward declare send / recv from Communication to use them within Task. I’ve read this question, which is similar and also provides good answers, but I’d like to avoid to place a pointer to Communication within Task. The best possible solution seems to me to introduce kind of forward declaration for the members of Communication, but I’m afraid that I don’t know how to accomplish this.
I’ve also thought about the class setup, whether it fits the purpose, but didn’t come up with a better solution yet.
You can put the declaration outside of the class. It doesn’t prevent the library to be header-only, as you could
inlinethose functions. You could arrange the functions like:And include
Task.impl.hto have the two task methods defined.