Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The basic intent behind a functor is to decouple the code that knows how to perform some kind of work from the code that knows when that work needs to be done (the classic example is associating a functor with a UI button).</p> <p>One minor benefit of the functor model is that plain old function pointers are already functors. No extra work is required to wrap them. I consider this a minor benefit because a) a function pointer is slightly less efficient than wrapping a direct call to the function, and b) I find that I almost always need to bind some form of state to whatever I'm wrapping, even if it's just the <code>this</code> pointer of a member function.</p> <p>The key advantage of a unary interface is that it serves as a lingua franca for producers and consumers of functors. You could, say, define functors to all have an <code>invoke()</code> member function, but then some other crowd would decide to standardise on <code>do()</code>, and yet another might go for <code>call()</code>. And all of these solutions involve more typing.</p> <p>Also, multiple member functions on a single "functor" are never strictly required. If some code needs to invoke multiple distinct operations, you can simply pass multiple functors. This provides good flexibility, since the operations may be coupled, or they may be completely unrelated.</p> <p>A decoupled example is a hash table that needs an equality-comparator and a hash function. In this case, the two functions could be unrelated: wrap the class's <code>operator==()</code> for equality and wrap a free function to compute the hash.</p> <p>A coupled example is a UI component that emits several distinct events. A single class might respond to all the events, or different classes might respond to different groups of events. Functors make it easy to choose either model, whereas requiring a single "interface" that defines callbacks for all the component's events is more awkward. Functors also make it much easier if a single object wants to handle events from two components differently, since you can give each component a different set of functor-wrapped member functions.</p> <p>Finally, wrapping existing functionality in a functor is well understood and widely supported by libraries such as boost.bind, whereas creating throw-away classes that implement <code>doX()</code> and <code>doY()</code> isn't. Plus, the new standard adds lambdas, which dramatically simplify the creation of functors.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload