Advertisement
WeltEnSTurm

Untitled

Sep 14th, 2011
379
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. // File: main.cpp, created on Sep 14, 2011 by WeltEnSTurm
  2.  
  3. #include "functor.hpp"
  4. #include <iostream>
  5. #include <string>
  6.  
  7. #define DEBUG
  8.  
  9. #ifdef DEBUG
  10. #define DEBUGDO(x) {x}
  11. #else
  12. #define DEBUGDO(x)
  13. #endif
  14.  
  15. void test1(std::string s){
  16.     std::cout << "Hello, I'm test1 with " << s << std::endl;
  17. }
  18.  
  19. void test2(std::string s){
  20.     std::cout << "Hello, I'm test2 with " << s << std::endl;
  21. }
  22.  
  23. void test3(std::string s){
  24.     std::cout << "Hello, I'm test3 with " << s << std::endl;
  25. }
  26.  
  27.  
  28. int main(){
  29.     DEBUGDO(
  30.             std::cout << "What?" << std::endl;
  31.     );
  32.  
  33.     functor<std::string> test;
  34.  
  35.     test += test1;
  36.     test += test2;
  37.     test += test3;
  38.  
  39.     test("good morning");
  40.  
  41.     return 0;
  42. }
  43. // File: functor.hpp, created on Sep 14, 2011 by WeltEnSTurm
  44.  
  45. #ifndef FUNCTOR_HPP_
  46. #define FUNCTOR_HPP_
  47.  
  48. #include <vector>
  49.  
  50. template<typename... T_args>
  51. class functor {
  52.     protected:
  53.         typedef void(*__func)(T_args...);
  54.         std::vector<__func> mFunctions;
  55.     public:
  56.         void operator () (T_args... a){
  57.             for(long i=0; i<(long)mFunctions.size(); i++)
  58.                 mFunctions[i](a...);
  59.         }
  60.  
  61.         void operator () (__func f){
  62.             mFunctions.push_back(f);
  63.         }
  64.  
  65.         void operator = (__func f){
  66.             clear();
  67.             mFunctions.push_back(f);
  68.         }
  69.  
  70.         void operator += (__func f){
  71.             mFunctions.push_back(f);
  72.         }
  73.  
  74.         void operator -= (__func f){
  75.             for(long i=0; i<mFunctions.size(); i++)
  76.                 if(mFunctions[i] == f){
  77.                     mFunctions.erase(mFunctions.begin() + i);
  78.                     break;
  79.                 }
  80.         }
  81.  
  82.         void clear(){
  83.             mFunctions.clear();
  84.         }
  85. };
  86.  
  87. #endif /* FUNCTOR_HPP_ */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement