Advertisement
Savior

C++11: function-wrapper

Sep 27th, 2015
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdexcept>
  3. using namespace std;
  4.  
  5. template <typename Signature>
  6. class OneTimer;
  7.  
  8. template <typename ReturnType, typename ...Args>
  9. class OneTimer<ReturnType(Args...)> {
  10.     bool usable;
  11.     ReturnType(*p)(Args...);
  12. public:
  13.     OneTimer(ReturnType(*func)(Args...)) : p(func), usable(true) { }
  14.     ReturnType operator()(Args ...args) {
  15.         if (usable) {
  16.             usable = false;
  17.             return p(args...);
  18.         }
  19.         throw std::runtime_error("Poshel nahuy");
  20.     }
  21. };
  22.  
  23. int random() {
  24.     return 42;
  25. }
  26.  
  27. int main() {
  28.     OneTimer<int()> a = random;
  29.     for (int i = 0; i < 10; ++i) {
  30.         try {
  31.             std::cout << a() << std::endl;
  32.         } catch(std::runtime_error &e) {
  33.             std::cerr << e.what() << std::endl;
  34.         }
  35.     }
  36.     return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement