Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <map>
- #include <iostream>
- #include <functional>
- #include <exception>
- #include <memory>
- using std::string;
- using std::map;
- using std::function;
- using std::shared_ptr;
- using std::exception;
- using std::runtime_error;
- using std::type_info;
- using std::cout;
- using std::endl;
- template<class Param> class action;
- class abstract_action
- {
- public:
- virtual ~abstract_action() {}
- template<class Param> void execute(Param param)
- {
- auto actn = dynamic_cast<action<Param>*>(this);
- if (!actn)
- throw runtime_error(string("Abstract_action::execute failed: got argument of type ") + typeid(Param).name() + " while expected type is " + param_typeid().name() + ".");
- actn->execute(param);
- }
- typedef shared_ptr<abstract_action> ref;
- protected:
- virtual const type_info& param_typeid() = 0;
- };
- template<class Param> class action: public abstract_action
- {
- public:
- typedef function<void(Param)> callback_type;
- action(callback_type theCallback) : callback(theCallback)
- {
- }
- void execute(Param param)
- {
- callback(param);
- }
- protected:
- const type_info& param_typeid() override
- {
- return typeid(Param);
- }
- private:
- callback_type callback;
- };
- template<class Param> abstract_action::ref make_action(function<void(Param)> cb)
- {
- return abstract_action::ref(new action<Param>(cb));
- }
- void main()
- {
- try
- {
- typedef map<string, abstract_action::ref> actions_map;
- actions_map actions;
- actions["IntArg"] = make_action<int>([] (int x) { cout << "Lambda A called with integer argument " << x << endl; });
- actions["StringArg"] = make_action<string>([] (string x) { cout << "Lambda B called with string argument " << x << endl; });
- actions["IntArg"]->execute(25);
- actions["StringArg"]->execute(string("YOBA"));
- actions["StringArg"]->execute("oops");
- } catch (exception& ex)
- {
- cout << ex.what() << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement