2

Say I have

double xSquared( const double )
{
    return x*x;
}

...
std::function<double (double)> func = &xSquared;
...

which works fine for the (more complicated) purposes I use this structure, up till now. Now I have a function that accepts a std::function of the above form and I need to create a new std::function that extends the original:

typedef std::function<double (double)> func1D;

double someFunction( const func1D &func, const double a )
{
    func1D extendedFunc = func/(x-a); // I know this is incorrect, but how would I do that?
    ...
}

So the mathematical equivalent is:

f(x) = x²

g(x) = f(x)/(x-a)

How can I accomplish this? Thanks for the help!

rubenvb
  • 74,642
  • 33
  • 187
  • 332
  • I have found this question, but I don't know how to translate it to my std c++0x case: http://stackoverflow.com/questions/2841619/function-composition-in-c Any help is much appreciated! – rubenvb Oct 24 '10 at 13:26

1 Answers1

8

Since you are using C++0x already, why not just use the lambda expression?

func1D divideByXMinusA(const func1D& f, double a) {
    return [=](double x) { return f(x)/(x-a); };
}

Edit: Using std::bind:

func1D divideByXMinusA_withBind(const func1D& f, double a) {
    using namespace std::placeholders;
    return std::bind(std::divides<double>(),
                          std::bind(f, _1),
                          std::bind(std::minus<double>(), _1, a));
}
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • All right, looks nice, but is there a way to do this only using bind and function? Trying to keep my compiler requirements to GCC 4.4 (which doesn't like lambda's very much :s). – rubenvb Oct 24 '10 at 13:33
  • @KennyTM: You are the man! Thanks for the lightning fast respose! Just out of curiosity: can this method be used to glue together more complicated functions (by replacing the `std::divides` and `std::minus` calls to more complicated things)? – rubenvb Oct 24 '10 at 13:46
  • 1
    I would like to to point out that both variants are not equivalent. In the first example you capture f by reference, in the second example the std::function object f refers to is copied. – sellibitze Oct 25 '10 at 06:38
  • @sellibitze: if you know how to do it better, I'm eager to learn, please post a new answer. Thanks. – rubenvb Oct 27 '10 at 15:33