title: C++ - Modify member function if argument (function) is given
body: <p>I am creating a class which takes as input arguments either <code>1</code> or <code>2</code> functions.</p>
  <p>My goal is that if only one function <code>func</code> is given then the member function <code>dfunc</code> is calculated using <code>num_dfunc</code> (which is the numerical derivative of <code>func</code> and is hardcoded inside the class). If two functions are given <code>func</code> and <code>analytical_dfunc</code> then the derivative is calculated using the analytical version. What is the best way to achieve this?</p>
  <p>This is a portion of my code</p>
  <pre class="lang-cpp prettyprint-override"><code>class MyClass
  {
  public:
      int dim = 2;
      vector&lt;double&gt; num_dfunc(vector&lt;double&gt; l0)
      {
          // Numerical gradient of the potential up to second order
          // #TODO This should be rewritten!
          vector&lt;double&gt; result(dim);
          double eps = 0.001;
  
          for (int i = 0; i &lt; dim; i++)
          {
              vector&lt;double&gt; lp2 = l0;
              lp2[i] += 2 * eps;
              vector&lt;double&gt; lp1 = l0;
              lp1[i] += eps;
              vector&lt;double&gt; lm1 = l0;
              lm1[i] -= eps;
              vector&lt;double&gt; lm2 = l0;
              lm2[i] -= 2 * eps;
              result[i] = (-func(lp2) + 8 * func(lp1) - 8 * func(lm1) + func(lm2)) / (12 * eps);
          }
          return result;
      }
      double (*func)(vector&lt;double&gt;);   // Potencial pointer
      vector&lt;double&gt; (*dfunc)(vector&lt;double&gt;);  // Gradient pointer
      MyClass(double (*func)(vector&lt;double&gt;))
      {
          this-&gt;func = func;
          // THIS IS WRONG
          this-&gt;dfunc = num_dfunc;
      }
      MyClass(double (*func)(vector&lt;double&gt;),double (*analytical_dfunc)(vector&lt;double&gt;))
      {
          this-&gt;func = func;
          // THIS IS WRONG
          this-&gt;dfunc = analytical_dfunc;
      }
  
  </code></pre>
  <p>This is a, somewhat, pythonic way of what I want to do.</p>
  <p>PS: This is not what I have so far, I tried many things but none of them worked.</p>
  <p>Edit : Error, on dfunc return type.
  Typo on analytical_<em>d</em>func</p>