Threads Module User's Guide : PART III Foundation Packages : Chapter 8 The Functor Package : Constructing Functors
Constructing Functors
To create a functor:
Construct a handle
Bind a callable object to that handle
The simplest way to do this is to bind the callable object handle when it is being constructed.
Example 66 shows the minimal code required for building and using a functor.
Example 66 – Creating and using a functor
#include <rw/functor/RWTFunctor.h>
void func(void);
int main(void) {
// build a functor to encapsulate function func
RWTFunctor<void()> functor = func;
//invoke the functor
functor();
return 0;
}
Analyzing Functor Requirements
The type of functor you build depends on the interface you want to expose. Just as with defining a function interface, two key questions need to be answered:
What parameters will the caller invoke the functor with?
What does the caller expect the functor to return?
RWTFunctor is a template class with a single template type that encapsulates this information. The template type specifies a function type of the form:
 
<return type>(<arg type 1>, <arg type 2>, …, <arg type N>)
Where <return type> is the type that the functor will return, and <arg type 1>, <arg type 2>, …, <arg type N> are the types of the arguments that the functor will take. For example, if you want to declare a functor that takes no arguments and returns void, the declaration of that functor would be:
 
RWTFunctor<void()> functor1;
Likewise, to declare a functor that takes a double and an int as arguments and returns an int, the declaration would be:
 
RWTFunctor<int(double, int)> functor2;
Just as with a normal function, the types in an RWTFunctor’s signature can be qualified. For example, if you wanted to declare an RWTFunctor that takes a const RWCString& argument, the declaration would be:
 
RWTFunctor<void(const RWCString&)> functor3;
Copying and Assigning Functors
Because functors use the handle-body idiom, copying functors follows the general rules discussed in “Handle-Body Mechanics.” When a handle class instance is copy-constructed from another handle class instance, the new handle is bound to the same body instance, if any, pointed to by the other handle.
Similarly, assigning one handle to another causes the left-hand instance to detach from its current representation, if any, and then binds it to the same body instance, if any, pointed-to by the right-hand instance.