user138668 - 6 months ago 40

C++ Question

I have designed a class of numerical array called

`ndarray`

`double *data`

`double log(double)`

`ndarray`

`ndarray`

My question is, since I don't want to rewrite the same code for ALL the mathematical functions of the form

`double fun(double)`

Answer

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).