최초작성 |
2005/07/29 18:23:33 |
Contents
DumFunctor
어쩌다보니 functor 를 짜게되서 적어둔다. functor 가 필요하면 boost::function 등의 잘구현된 놈을 가져다 쓰는것이 좋다. 이 구현은 최대한 간단하게 만든것이라서 STLlike 하지도 않고..
인자갯수에 맟춰서 클래스를 더 만들어야 하는등 문제가 많지만 boost 를 쓰지 못할때 간단히 써먹으려고 만들었다.
1 #include <memory> 2 #include <string> 3 #include <iostream> 4 using namespace std; 5 6 template<typename R> 7 struct DumFunctor0 8 { 9 typedef R(*func_type)(); 10 func_type f_; 11 12 DumFunctor0(func_type f) : f_(f) {} 13 R operator()() 14 { 15 return f_(); 16 } 17 }; 18 19 template<typename R,typename A1> 20 struct DumFunctor1 21 { 22 typedef R(*func_type)(A1); 23 func_type f_; 24 const A1& a1_; 25 26 DumFunctor1(func_type f,const A1& a1) : f_(f), a1_(a1) {} 27 R operator()() 28 { 29 return f_(a1_); 30 } 31 }; 32 33 template<typename R,typename A1, typename A2> 34 struct DumFunctor2 35 { 36 typedef R(*func_type)(A1,A2); 37 func_type f_; 38 const A1& a1_; 39 const A2& a2_; 40 41 DumFunctor2(func_type f,const A1& a1,const A2& a2) : f_(f), a1_(a1),a2_(a2) {} 42 R operator()() 43 { 44 return f_(a1_,a2_); 45 } 46 }; 47 48 49 void foo0() { cout << "foo0" << endl; } 50 51 int foo1(int x) { cout << "foo1" << endl; return x; }; 52 string bar1(const char* x) { cout << "bar1" << endl; return string(x); } 53 54 double foo2( float x, float y) { cout << "foo2" << endl; return x*y; } 55 56 57 58 int main() 59 { 60 DumFunctor0<void> call_foo0(foo0); 61 call_foo0(); 62 63 DumFunctor1<int,int> call_foo1(foo1,100); 64 call_foo1(); 65 66 DumFunctor1<string,const char*> call_bar1(bar1, "hahaha"); 67 call_bar1(); 68 69 DumFunctor2<double,float,float> call_foo2(foo2,100.0f, 200.0f); 70 call_foo2(); 71 } 72
callback 으로
DumFunctor 의 인스턴스를 다른 함수에 인자로 넘기는것도 가능하다. 이때 DumFuctor<...> 를 인자로 받는함수도 템플릿함수로 만들어서 다양한타입의 DumFunctor 를 하나의 함수로 처리하는것도 가능( 아래 예의 bar<F> )
1 int foo(int x, int y) 2 { 3 return x+y; 4 } 5 6 template<typename F> 7 void bar(F f) 8 { 9 cout << f() << endl; 10 } 11 12 void bar2(DumFunctor2<int,int,int> f) 13 { 14 cout << f() << endl; 15 } 16 17 int main() 18 { 19 DumFunctor2<int,int,int> call_foo(foo,100,200); 20 bar(call_foo); 21 22 bar2(call_foo); 23 }
