2006년 3월 6일 월요일

function object (= functor )

C++에 도입된 기능이다.
특히 C++ STL에서 사용된다.
callback function의 용도로 많이 쓰인다.
pointer to function와 같은 기능을 갖지만 몇 가지 장점이 있다.

http://www.sgi.com/tech/stl/functors.html
http://gethelp.devx.com/techtips/cpp_pro/10min/10min0100.asp
http://en.wikipedia.org/wiki/Function_object
. 장점
. result를 global, local variable이 아닌 member function에 가지고 있으므로 안전하다. (여러곳에서 call하다가 결과가 사라지는 일이 없을 것이므로)
. compiler가 지원한다면 inline이 가능하다.
. 보통 생성자, 소멸자를 안 쓰므로 overhead가 없다.

. STL에서 사용되는 곳
#include // for greater<> and less<>
#include //for sort()
sort()
for_each()
greater()
less()

. 예제 코드
// vector V의 모든 값을 accumulate한다.
struct adder : public unary_function
{
adder() : sum(0) {}
double sum;
void operator()(double x) { sum += x; }
};

vector V;
...
adder result = for_each(V.begin(), V.end(), adder()); [3]
cout << "The sum is " << result.sum << endl;

. Languages
. Smalltalk : one of the first language to support functor
. C : function pointer
. C++ : overloads the function call operator by defining an operator() member function, class type functor, operator()
. Java : deriving from the interface, inheritance model of functor
. Python : __call__()
. Lisp
. ML : Mapping from module to module
. Prolog : function symbol

댓글 없음:

댓글 쓰기