组合std :: function对象 [英] Combining std::function objects

查看:142
本文介绍了组合std :: function对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有

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

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

对于(更复杂的) , 至目前为止。现在我有一个接受上述表单的std :: function的函数,我需要创建一个新的std ::函数来扩展原始的:

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

double someFunction(const func1D& func,const double a)
{
func1D extendedFunc = func /(x-a); //我知道这是不正确的,但我该怎么做?
...
}

所以数学等价物是:


f(x)=x²

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

我该如何做到这一点?感谢您的帮助!

解决方案

既然您已经使用了C ++ 0x,为什么不使用lambda表达式呢?

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





编辑:使用 std :: bind

  func1D divideByXMinusA_withBind(const func1D& f,double a ){
using namespace std :: placeholders;
返回std :: bind(std :: divides< double>(),
std :: bind(f,_1),
std :: bind(std :: minus< double> (),_1,a));
}


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

这篇关于组合std :: function对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆