title: How to apply function to all elements in array (in C++ template class)
body: <p>I have a template class that stores an array of numbers and I want to apply existing (scalar) functions to every element. For example, if we assume my class is std::vector, then I want to be able to call (for example) the std::cos function on all elements.</p>
  
  <p>Maybe a call would look like this:</p>
  
  <pre><code>std::vector&lt;float&gt; A(3, 0.1f);
  std::vector&lt;float&gt; B = vector_function(std::cos, A);
  </code></pre>
  
  <p><strong>N.B. I must also handle std::complex&lt;> types (for which the appropriate complex std::cos function is called).</strong> </p>
  
  <p>I found <a href="https://stackoverflow.com/questions/9112866/passing-a-complex-function-variants-as-arguments">this answer</a> which suggests taking the function type as a template parameter:</p>
  
  <pre><code>template&lt;typename T, typename F&gt;
  std::vector&lt;T&gt; vector_function(F func, std::vector&lt;T&gt; x)
  </code></pre>
  
  <p>However, I couldn't get this to work at all (maybe because functions like std::sin and std::cos are both templated and overloaded?).</p>
  
  <p>I also tried using <code>std::transform</code>, but this quickly became very ugly. For non-complex types, I managed to get it working using a typedef:</p>
  
  <pre><code>std::vector&lt;float&gt; A(2, -1.23f);
  typedef float (*func_ptr)(float);
  std::transform(A.begin(), A.end(), A.begin(), (func_ptr) std::abs);
  </code></pre>
  
  <p>However, attempting the same trick with std::complex&lt;> types caused a run-time crash.</p>
  
  <p>Is there a nice way to get this working? I have been stuck on this for ages.</p>