Skip to content

Instantly share code, notes, and snippets.

@bo0ts
Created January 11, 2013 10:26
Show Gist options
  • Save bo0ts/4509591 to your computer and use it in GitHub Desktop.
Save bo0ts/4509591 to your computer and use it in GitHub Desktop.
Dynamic functors with references
#include <boost/function.hpp>
#include <boost/ref.hpp>
#include <iostream>
class X {
public:
void foobar() {
// do stuff
// if func_ is set, call it
if(func_) { func_(23); }
}
template<typename Functor>
void set_on_foobar(Functor f) { func_ = f; }
void remove_on_foobar() { func_ = boost::function<int(int)>(); }
private:
boost::function<void(int)> func_;
};
struct my_f {
my_f(int i):i_(i){}
~my_f(){std::cout << "destructed" << std::endl;}
void operator()(int x) const { std::cout << "Operator() " << x+i_ << "\n"; }
int i_;
};
int main()
{
X x;
my_f f(7);
x.set_on_foobar(boost::ref(f)); // with a functor
x.foobar();
f.i_=100;
x.foobar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment