Skip to content

Instantly share code, notes, and snippets.

@mihids
Last active November 16, 2016 13:36
Show Gist options
  • Save mihids/a55d5b5e00cf043d28e3 to your computer and use it in GitHub Desktop.
Save mihids/a55d5b5e00cf043d28e3 to your computer and use it in GitHub Desktop.
boost bind and boost function for callbacks
#include <cstdlib>
#include <boost/bind.hpp>
#include <boost/function.hpp>
class A {
public:
void print(const std::string &s) {
std::cout << s << std::endl;
}
void printTwoArgs(const std::string &s, const int iNumber) {
std::cout << s << " " << iNumber << std::endl;
}
};
// holds any arity 0 callable "thing" which returns void
typedef boost::function<void() > callback;
class B {
public:
void set_callback(callback cb) {
m_cb = cb;
}
void do_callback() {
m_cb();
}
private:
callback m_cb;
};
void regular_function() {
std::cout << "regular!" << std::endl;
}
int main() {
A a;
B b;
std::string s("message");
// you forget the "&" here before A::print!
// boost::bind returns boost::function<void(const std::string &)>
b.set_callback(boost::bind(&A::print, &a, s));
// essentially it's similar to
// boost::function<void(const std::string &)> newFunc = boost::bind(&A::print, &a, s);
b.do_callback();
// b.set_callback(newFunc);
b.set_callback(boost::bind(&A::printTwoArgs, &a, s, 10));
b.do_callback();
// this will work for regular function pointers too, yay!
b.set_callback(regular_function);
b.do_callback();
}
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
class A {
public:
void print(const string &s) {
std::cout << s << std::endl;
}
void printTwoArgs(const std::string &s, const int iNumber) {
std::cout << s << " " << iNumber << std::endl;
}
};
typedef void (A::*callbackType1)(const string &);
typedef void (A::*callbackType2)(const string &, const int);
class B {
public:
B(A & aRef) : aRef(aRef) {
}
void set_callback1(callbackType1 cb) {
m_cb1 = cb;
}
void set_callback2(callbackType2 cb) {
m_cb2 = cb;
}
void do_callback1(const string & str) {
(aRef.*m_cb1)(str);
}
void do_callback2(const string & str, const int iNum) {
(aRef.*m_cb2)(str, iNum);
}
private:
A &aRef;
callbackType1 m_cb1;
callbackType2 m_cb2;
};
int main() {
A a;
B b(a);
b.set_callback1(&A::print);
b.set_callback2(&A::printTwoArgs);
b.do_callback1("message");
b.do_callback2("message with arg", 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment