Advertisement
runewalsh

Что-то с шоблонами

Mar 15th, 2015
513
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include <string>
  2. #include <map>
  3. #include <iostream>
  4. #include <functional>
  5. #include <exception>
  6. #include <memory>
  7.  
  8. using std::string;
  9. using std::map;
  10. using std::function;
  11. using std::shared_ptr;
  12. using std::exception;
  13. using std::runtime_error;
  14. using std::type_info;
  15. using std::cout;
  16. using std::endl;
  17.  
  18. template<class Param> class action;
  19.  
  20. class abstract_action
  21. {
  22. public:
  23.     virtual ~abstract_action() {}
  24.  
  25.     template<class Param> void execute(Param param)
  26.     {
  27.         auto actn = dynamic_cast<action<Param>*>(this);
  28.         if (!actn)
  29.             throw runtime_error(string("Abstract_action::execute failed: got argument of type ") + typeid(Param).name() + " while expected type is " + param_typeid().name() + ".");
  30.         actn->execute(param);
  31.     }
  32.  
  33.     typedef shared_ptr<abstract_action> ref;
  34.  
  35. protected:
  36.     virtual const type_info& param_typeid() = 0;
  37. };
  38.  
  39. template<class Param> class action: public abstract_action
  40. {
  41. public:
  42.     typedef function<void(Param)> callback_type;
  43.  
  44.     action(callback_type theCallback) : callback(theCallback)
  45.     {
  46.     }
  47.  
  48.     void execute(Param param)
  49.     {
  50.         callback(param);
  51.     }
  52.  
  53. protected:
  54.     const type_info& param_typeid() override
  55.     {
  56.         return typeid(Param);
  57.     }
  58.  
  59. private:
  60.     callback_type callback;
  61. };
  62.  
  63. template<class Param> abstract_action::ref make_action(function<void(Param)> cb)
  64. {
  65.     return abstract_action::ref(new action<Param>(cb));
  66. }
  67.  
  68. void main()
  69. {
  70.     try
  71.     {
  72.         typedef map<string, abstract_action::ref> actions_map;
  73.         actions_map actions;
  74.         actions["IntArg"] = make_action<int>([] (int x) { cout << "Lambda A called with integer argument " << x << endl; });
  75.         actions["StringArg"] = make_action<string>([] (string x) { cout << "Lambda B called with string argument " << x << endl; });
  76.  
  77.         actions["IntArg"]->execute(25);
  78.         actions["StringArg"]->execute(string("YOBA"));
  79.         actions["StringArg"]->execute("oops");
  80.  
  81.     } catch (exception& ex)
  82.     {
  83.         cout << ex.what() << endl;
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement