user138668 user138668 - 8 months ago 52
C++ Question

How to overload all math functions simultaneously for a class of numerical arrays

I have designed a class of numerical array called

, which basically contains a double array member
double *data
. I have overloaded the math function
double log(double)
such that it is a friend of the class and when called with an input
object, returns an object of
of the same size as the input array with its elements the logarithm of the input array.
My question is, since I don't want to rewrite the same code for ALL the mathematical functions of the form
double fun(double)
, how can I overload all of them simultaneously?


One approach would be to add a member to your ndarray class for applying a function to each element and returning the result. This doesn't overload all the math functions, but lets you do things like ndarray.apply(sin). Perhaps something like the following (untested):

class myNdarray
  template <typename T>
  myNdarray apply(T func) const
    myNdarray ret(*this);
    for (auto& elm: ret) elm = func(elm);
    return ret;

In the above I use C++11 auto and I make a few assumptions about how your type behaves, but you could implement this without C++11. You could also remove the template type T and instead specify an explicit type (perhaps a function only taking a single double and returning a double would be safer).