Add support for using std::function callbacks instead of C-pointers #35
+28
−3
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
When writing more structured Arduino code, it may be desirable to have an instance of
MqttClient
be encapsulated inside another object e.g.MyMqttIntegration
. In this case, the exclusive use of C-pointers for message callbacks becomes a problem since a member function ofMyMqttIntegration
cannot be presented as a C-pointer. It is possible to cast a captureless lambda as a C-pointer, but this has it's own limitations.This PR provides a solution: the current C-pointer API remains the default, but by defining
MQTT_CLIENT_STD_FUNCTION_CALLBACK
the library swaps to usingstd::function
s.Such a callback can then be defined by a lambda or by using
std::bind
on a member function.Example setting of message callback when
MQTT_CLIENT_STD_FUNCTION_CALLBACK
is defined:Including a pointer to the source
MqttClient
affords a little extra flexibility in case multipleMqttClient
s are used which share the same callback function.