Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can C++ functors be preferable to objects with named methods?
    text
    copied!<p>I recently have got excited by functors and been using them all over the place. Then the situation arose where I needed my functor to perform two different operations and I thought about adding another method to my functor (not overloading the () operator). Whether this is bad practice or not I am not sure (perhaps you could tell me), but it got me thinking about why I am using functors in the first place and not just objects. So my question is:</p> <p><strong>Is there anything special about overloading the () operator or is it just very slightly more syntactically appealing than using normal named methods?</strong> </p> <p><strong>Update:</strong></p> <p>Firstly, I know why functors may be preferable to function pointers as explained in other questions. I want to know why they can be preferable to objects with named methods.</p> <p>Secondly, as for an example of when I wanted to use another possibly named method of my functor: Basically I have two functions, one which calculates something called the modularity of a graph partition - <code>compute_modularity()</code>, and another which computes the gain in modularity after some change of the partition<code>compute_modularity_gain()</code>. I thought I could pass these functions as part of the same functor into an optimisation algorithm, with the gain as a named function. The reason I don't just pass two functors into the algorithm, is that I want to enforce that <code>compute_modularity_gain()</code> is used only in conjuction with <code>compute_modularity()</code> and not another functor e.g. <code>compute_stability()</code> (which should only be used with <code>compute_stability_gain()</code>. In other words, the gain function must be tightly coupled with its sibling function. If there is another way I can enforce this constraint then please let me know.</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