开发者

Combining std::function objects

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!


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));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜