Skip to content

Instantly share code, notes, and snippets.

@makomweb
Created June 3, 2014 16:11
Show Gist options
  • Save makomweb/3b45f87880e6368b1307 to your computer and use it in GitHub Desktop.
Save makomweb/3b45f87880e6368b1307 to your computer and use it in GitHub Desktop.
Late binding playground
#include <iostream>
#include <map>
#include <algorithm>
#include <functional>
#include <memory>
using namespace std;
using namespace std::placeholders;
class receiver
{
function<void(receiver*, const string&)> func_;
void print_message(const string& arg)
{
cout << "Yeah, " << arg.c_str() << endl;
}
void ignore_message(const string& arg)
{
cout << "ZzzzZzzz" << endl;
}
public:
receiver()
{
put_to_awake();
}
void handle_message(const string& arg)
{
func_(this, arg);
}
void put_to_awake()
{
func_ = bind(&receiver::print_message, this, _2);
}
void put_to_ignore()
{
func_ = bind(&receiver::ignore_message, this, _2);
}
};
int main()
{
receiver obj;
obj.handle_message(string("one"));
obj.put_to_ignore();
obj.handle_message(string("two"));
obj.put_to_awake();
obj.handle_message(string("three"));
// Outputs:
// Yeah, one
// ZzzzZzzz
// Yeah, three
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment