Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The way I've seen this done is to write callback functions. So you would write the logic part once, much like you have in your second text block. You would also define functions A, B, C, D, E, and F. </p> <p>In your logic function, you would pass in both the parameters required and pointers to the callback functions. Then, in the logic function, you would call these callbacks and pass them the parameters they need.</p> <p>Quite honestly, this seems like it would be more work in the end. You would maintain a single point of truth for your logic, but function pointers can be a massive pain and reduce the readability of your code. </p> <p>For the sake of providing as much information as possible, an example:</p> <pre><code>int addTwoNumbers(int a, int b) { //A simple adding function return a + b; } int subtractTwoNumbers(int a, int b) { //A simple subtracting function return a - b; } /* * This is the fun one. The first argument is a pointer to a function. The other * arguments are the numbers to do math with. They aren't as important. * The important part is that, so long as the function declaration matches the one here * (so a function that returns an int and takes in two ints as arguments) it can be * used by this function */ void math(int (*mathFunc)(int, int), int one, int two) { cout &lt;&lt; *mathFunc(one, two); } int main(int argc, char* argv[]) { int whichMath = 0; //Assume 1 is add, 2 is subtract if(whichMath == 1) { math(&amp;addTwoNumbers, 5, 6); //we're going to add 5 and 6 } else { math(&amp;subtractTwoNumbers, 5, 6); // we're going to subtract 5 and 6 } } </code></pre> <p>If that makes <em>NO</em> sense, then you are welcome to join the legions of us who struggle with function pointers. Again, I would say that you should just write the two separate functions, as you can see how ugly this will get. </p> <p>As a disclaimer, I have not compiled this code. I'm at work and there is no c++ compiler on these machines.</p> <p>I have used this site heavily in the past for reference on function pointers: <a href="http://www.newty.de/fpt/fpt.html#defi" rel="nofollow">http://www.newty.de/fpt/fpt.html#defi</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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