Thursday, January 7, 2010

Define a functor

In C you have the classical pointer to function which allows you to store a pointer to a parametric function f. Then you can pass the pointer to another function g, which will use f. A typical example is the cmp function you use to sort a generic array of type T elements. The problem with pointer to function is that you don't have a strong type system to check the signature of the function and this can generate potential horrid bugs.

In C++ and STL you typically define a functor object which had the type system check but is limited to unary, binary or ternary functions.

In Boost you resolve this problem by using the Boost Function library, which allows you to define a type checked function object with unlimited number of parameters.

No comments:

Post a Comment