Created
August 24, 2017 20:10
-
-
Save mpenick/5035fa76f637ef6ddc7396c3cb7ac4fa to your computer and use it in GitHub Desktop.
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 <iostream> | |
#include <functional> | |
using namespace std; | |
template<class T> | |
class Handler { | |
public: | |
typedef std::function<void(T&)> Callback; | |
Handler<T>& success(const Callback& callback) { | |
on_success_ = callback; | |
return *this; | |
} | |
Handler<T>& error(const Callback& callback) { | |
on_error_ = callback; | |
return *this; | |
} | |
bool run() { | |
if (!on_success_ || !on_error_) { | |
return false; | |
} | |
return T::on_run(); | |
} | |
bool cancel() { | |
return T::on_cancel(); | |
} | |
protected: | |
void completed() { | |
on_success_(*static_cast<T*>(this)); | |
} | |
void failed() { | |
on_error_(*static_cast<T*>(this)); | |
} | |
private: | |
Callback on_success_; | |
Callback on_error_; | |
}; | |
struct Host { }; | |
class Resolver : public Handler<Resolver> { | |
public: | |
bool on_run() { | |
completed(); | |
return true; | |
} | |
bool on_cancel() { | |
return true; | |
} | |
}; | |
class Connector : public Handler<Connector> { | |
public: | |
bool on_run() { | |
completed(); | |
return true; | |
} | |
bool on_cancel() { | |
return true; | |
} | |
}; | |
int main() { | |
Resolver() | |
.success([](Resolver&) { | |
cout << "resolved" << endl; | |
Connector() | |
.success([](Connector&) { | |
cout << "connected" << endl; | |
}) | |
.error([](Connector&){ | |
cout << "failed to connect" << endl; | |
}) | |
.run(); | |
}) | |
.error([](Resolver&) { | |
cout << "failed to resolve" << endl; | |
}) | |
.run(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment