Of course. Here is a complete and robust C++ implementation based on your detailed prompt.
This solution uses the Curiously Recurring Template Pattern (CRTP) to achieve static polymorphism, which avoids the overhead of virtual function calls. It's designed for a single-threaded environment, so it omits thread-synchronization primitives like mutexes for maximum efficiency.
Complete Implementation
#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include <cstdint>
#include <sstream>
#include <utility>
// --- Template Base Class Implementation ---
template <typename Derived>
class CallbackCommunicator {
public:
// Public API for users of the communicator
/**
* @brief Sends a message and registers a callback for the response.
* @param message The text data to send.
* @param callback The function to execute when a response is received.
*/
void sendMessage(const std::string& message, std::function<void(const std::string&)> callback) {
// Ensure the derived class is connected before sending
if (!derived()->isConnected()) {
std::cerr << "Warning: Attempted to send message while disconnected. Invoking callback with empty response." << std::endl;
if (callback) {
callback(""); // Fulfill the contract by calling back
}
return;
}
const uint64_t id = m_nextId++;
m_pendingCallbacks[id] = std::move(callback);
// Format the message with the ID. A simple "ID:message" format.
std::ostringstream oss;
oss << id << ":" << message;
// Use the derived class's transport to send the data
derived()->sendText(oss.str());
}
protected:
// Protected API for the Derived (CRTP) class to call
/**
* @brief To be called by the derived class when a message is received from the transport.
* It finds and executes the corresponding callback.
* @param id The unique ID of the message being responded to.
* @param response The response data.
*/
void onMessage(uint64_t id, const std::string& response) {
auto it = m_pendingCallbacks.find(id);
if (it != m_pendingCallbacks.end()) {
// Execute the callback
it->second(response);
// Clean up the stored callback
m_pendingCallbacks.erase(it);
} else {
std::cerr << "Warning: Received response for unknown message ID " << id << std::endl;
}
}
/**
* @brief To be called by the derived class when the transport disconnects.
* This invokes all pending callbacks with an empty string to signal an error/timeout.
*/
void onDisconnect() {
std::cout << "--- Disconnection event ---" << std::endl;
// Move callbacks to a temporary map to avoid issues if a callback
// tries to modify the map itself (though unlikely in single-threaded app).
auto callbacksToInvoke = std::move(m_pendingCallbacks);
m_pendingCallbacks.clear();
for (const auto& pair : callbacksToInvoke) {
std::cout << "Invoking pending callback for ID " << pair.first << " due to disconnect." << std::endl;
pair.second(""); // Call with empty string to signal failure
}
}
// Protected destructor to prevent deleting a derived class through a base pointer.
~CallbackCommunicator() = default;
private:
// Helper function to safely cast 'this' to the derived type.
Derived* derived() {
return static_cast<Derived*>(this);
}
uint64_t m_nextId = 1; // Start IDs from 1 for clarity
std::unordered_map<uint64_t, std::function<void(const std::string&)>> m_pendingCallbacks;
};
// --- Example Usage ---
// Forward declaration is needed for MyTransport to know about MyCommunicator
class MyCommunicator;
/**
* @class MyTransport
* @brief A mock transport implementation.
* In a real application, this would handle TCP, WebSockets, etc.
*/
class MyTransport {
public:
MyTransport() : m_connected(true) {}
// Method to link this transport to its owner communicator
void connect(MyCommunicator* owner) {
m_owner = owner;
}
// Method required by the CRTP base class
void sendText(const std::string& text) {
std::cout << "[Transport] Sending: \"" << text << "\"" << std::endl;
// --- SIMULATION ---
// In a real-world scenario, this would go over the network.
// Here, we'll just parse it and immediately "receive" a response.
size_t colon_pos = text.find(':');
if (colon_pos != std::string::npos) {
uint64_t id = std::stoull(text.substr(0, colon_pos));
std::string original_msg = text.substr(colon_pos + 1);
// Don't respond to "ping" to simulate a timeout later
if (original_msg != "ping") {
std::string response = "ACK for \"" + original_msg + "\"";
simulateReceive(id, response);
}
}
}
// Method required by the CRTP base class
bool isConnected() const {
return m_connected;
}
// --- SIMULATION METHODS ---
void simulateReceive(uint64_t id, const std::string& response);
void simulateDisconnect() {
m_connected = false;
if (m_owner) {
// Let the owner know about the disconnection.
// This will trigger the onDisconnect logic in the base class.
void processDisconnect();
}
}
private:
bool m_connected;
MyCommunicator* m_owner = nullptr; // Pointer to the owner to send data back up
};
/**
* @class MyCommunicator
* @brief The final communicator class implementing the CRTP pattern.
* It owns the transport and provides the methods required by the base class.
*/
class MyCommunicator : public CallbackCommunicator<MyCommunicator> {
// Allows base class to call private/protected methods if needed. Good practice.
friend class CallbackCommunicator<MyCommunicator>;
public:
MyCommunicator() {
// Connect the transport layer to this communicator instance
m_transport.connect(this);
}
// Public method to simulate a disconnection for the example
void triggerDisconnect() {
m_transport.simulateDisconnect();
// After transport confirms disconnection, we notify the base class
this->onDisconnect();
}
// Public method for transport to push received data
void processIncomingMessage(uint64_t id, const std::string& response) {
std::cout << "[Communicator] Processing incoming message for ID " << id << std::endl;
// This calls the protected base class method
this->onMessage(id, response);
}
private:
// These are the methods the CRTP base will call via `derived()->`
void sendText(const std::string& text) {
m_transport.sendText(text);
}
bool isConnected() const {
return m_transport.isConnected();
}
MyTransport m_transport;
};
// Definition of MyTransport::simulateReceive needs full MyCommunicator definition
void MyTransport::simulateReceive(uint64_t id, const std::string& response) {
if (m_owner) {
std::cout << "[Transport] Simulating response for ID " << id << std::endl;
m_owner->processIncomingMessage(id, response);
}
}
// --- Main function to demonstrate usage ---
int main() {
MyCommunicator comms;
std::cout << "--- Sending messages ---" << std::endl;
// Send a message and provide a lambda callback
comms.sendMessage("Hello", [](const std::string& response) {
std::cout << "[Callback 1] Response received: \"" << response << "\"" << std::endl;
});
// Send another message
comms.sendMessage("World", [](const std::string& response) {
std::cout << "[Callback 2] Response received: \"" << response << "\"" << std::endl;
});
// Send a message that we will simulate a timeout for (transport won't respond)
comms.sendMessage("ping", [](const std::string& response) {
if (response.empty()) {
std::cout << "[Callback 3] Response for 'ping' was empty, likely a disconnect or timeout." << std::endl;
} else {
std::cout << "[Callback 3] Response for 'ping' received: \"" << response << "\"" << std::endl;
}
});
std::cout << "\n--- All messages sent. Awaiting responses... ---\n" << std::endl;
// Simulate the transport disconnecting
comms.triggerDisconnect();
std::cout << "\n--- Trying to send after disconnect ---" << std::endl;
comms.sendMessage("This will fail", [](const std::string& response){
if (response.empty()) {
std::cout << "[Callback 4] Could not send message as we are disconnected. Callback invoked correctly." << std::endl;
}
});
return 0;
}
Explanation
-
CallbackCommunicator<Derived> (The Base Class):
- This is the core template. It has no idea what the
Derived class is, other than that it will provide sendText() and isConnected() methods.
sendMessage() is the public-facing API. It generates a unique ID, stores the std::function callback in an std::unordered_map, formats the message with the ID, and uses the CRTP derived()->sendText() call to pass the formatted message to the transport layer.
onMessage() and onDisconnect() are protected. They are intended to be called only by the Derived class when events occur in the transport layer. onMessage looks up the callback and executes it, while onDisconnect clears out all pending callbacks.
- The
derived() helper is a common CRTP idiom that makes the code cleaner by hiding the static_cast.
-
MyTransport (The Transport Layer):
- This is a mock class. In a real application, it would manage a socket or other communication channel.
- It holds a pointer back to its owner (
MyCommunicator*) so it can push events (like received messages or disconnections) back up.
sendText() simulates sending data. In this example, it immediately "receives" a response and calls back to the owner via simulateReceive.
-
MyCommunicator (The Derived Class):
- This class inherits from
CallbackCommunicator<MyCommunicator>, which is the essence of CRTP.
- It owns an instance of
MyTransport.
- It provides the
sendText() and isConnected() methods that the base class requires, simply by delegating those calls to its m_transport member.
- It has public methods like
processIncomingMessage() that the transport layer can call. These methods, in turn, call the protected onMessage() and onDisconnect() methods of the base class, completing the communication loop.
-
main() (The Driver Code):
- It creates an instance of .