Created
January 11, 2013 10:26
-
-
Save bo0ts/4509591 to your computer and use it in GitHub Desktop.
Dynamic functors with references
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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