title: Create member function according to variable value in C++
body: <p>The original code is too complicated so I abstract the problem as following:  </p>
  
  <pre><code>class A {
    public:
      A (int p): _p{p} {}
  
      float computeA (float a) {
        if (_p == 0)
          return 0.1f + expf(a);
        else if (_p == 1)
          return 0.2f + sqrtf(a);
        else if (_p == 2)
          return 0.3f + sinf(a);
        return 0.4f +cosf(a);
      }
  
      float accumulate() {
        ...
        for(...) {
          int temp = computeA();
          // other calculations...
        }
        ...
      }
  
      ...
  
    private:
      const int _p;
  };
  </code></pre>
  
  <p><strong>_p</strong> is a constant member in <strong>A</strong>, and can be only either 0, 1, 2, or 3. The calculation in <strong>computeA()</strong> depends on the value of <strong>_p</strong>. Since <strong>_p</strong> is already known when creating <strong>A</strong>, I wonder if there is a proper way to avoid the "if" conditions in the code. </p>
  
  <p>Polymorphism is not practical (or it is?) for just changing one line of code for each child class (<strong>A</strong> has a dozen of member functions, and only <strong>computeA()</strong> makes a difference). Another issue might be the performance since the simple <strong>computeA()</strong> is frequently called in a large loop of the heavy <strong>accumulate()</strong>. Would overhead of polymorphic function calls become unacceptable?</p>
  
  <p>Thanks,</p>