简体   繁体   English

组合std :: function对象

[英]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: 现在我有一个接受上述形式的std :: function的函数,我需要创建一个扩展原始的新的std :: function:

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² f(x)=x²

g(x) = f(x)/(xa) g(x)= f(x)/(xa)

How can I accomplish this? 我怎么能做到这一点? Thanks for the help! 谢谢您的帮助!

Since you are using C++0x already, why not just use the lambda expression? 由于您已经使用C ++ 0x,为什么不使用lambda表达式呢?

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

Edit: Using std::bind : 编辑:使用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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM