我有以下類設置(這裏只與相關內容):C++成員回調與向前聲明
// 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);
};
我的目標是一種提供在Communication
之內的一個獨立的通信層,讓任務相互通信。接收者列表在taskMap
(發送者不知道接收者的發佈 - 訂閱類型)內定義。
爲此,我的想法是使用從Task
到Communication
的回調函數(例如std::bind
或類似的)。但是,我無法執行此操作,因爲無論何時我將Communication
標頭內的Task
編譯失敗,這是由於通告包含在內。
所以我不確定如何從Communication
轉發聲明send
/recv
在Task
內使用它們。我已閱讀this問題,這是類似的,也提供了很好的答案,但我想避免在Task
內放置指向Communication
的指針。在我看來,最好的解決方案是爲Communication
的成員引入一種前向聲明,但是我擔心我不知道如何實現這一點。
我也想過班級設置,無論是否符合目的,但沒有提出更好的解決方案。
可您拆分代碼分成單獨的塊所以很清楚哪些東西在頭聲明?也許一個評論顯示你希望能夠插入回調函數? – Oktalist
完成後,還添加了當前的include和關於包含編譯失敗的註釋。 –
不錯。現在'Task :: send()'和'recv()'從哪裏獲得'Communication'的實例?你真的在類定義中內聯定義這些函數,還是在單獨的'Task.cpp'文件中定義? (如果您可以簡單回答這些問題,則無需編輯代碼。) – Oktalist