Rogue Wave banner
Previous fileTop of DocumentContentsIndex pageNext file
Threads Module User's Guide

8.3 Invoking Functors

Invoking a functor is straightforward. Each functor class overloads operator() to provide a style of invocation identical to that of a function call, as shown in Example 67.

Example 67: Invoking functors

8.3.1 Running Unknown Functions

Example 68 takes advantage of the type independence of functors to implement a timer. It starts the clock, runs a function, and reports how long it takes to execute. This timer takes a functor of type RWTFunctor<void()>, so it can handle any function that can be encapsulated by such a functor. Because a return value can be ignored for the purpose of timing, it is possible to specify a functor that can handle functions either with or without a return value. Notice how simple it is to do something with functors that would be too difficult to attempt otherwise. Without functors, you would have to write a timer for every possible combination of function return type and argument types.

The timer doesn't know anything about the function it is launching. Only the callee software that builds the functor needs to know about the function it encapsulates. In this example, the same routine builds the functors and runs them, but it could just as easily be an entirely separate callee building the functors and passing them to the timer, serving as the caller.

Example 68: Building a timer with functors

//1

The timer() function takes a functor of type RWTFunctor<void()> and returns a double.

//2

timer() runs RWTFunctor<void()>'s operator(), which invokes the functor instance and launches its encapsulated function.

//3

Constructs a handle instance, work_functor, for a functor object.

//4

Hands the functor work_functor to the timer() function. When timer() runs work_functor, it launches the encapsulated function, work().



Previous fileTop of DocumentContentsNo linkNext file

Copyright © Rogue Wave Software, Inc. All Rights Reserved.

The Rogue Wave name and logo, and SourcePro, are registered trademarks of Rogue Wave Software. All other trademarks are the property of their respective owners.
Provide feedback to Rogue Wave about its documentation.