其他分享
首页 > 其他分享> > c-使用boost :: bind将成员函数绑定到boost :: bisect吗?

c-使用boost :: bind将成员函数绑定到boost :: bisect吗?

作者:互联网

我以前在this上遇到过问题,但现在可以正常工作了.

现在,我一直在跟踪问题.在使用相同的函数调用boost :: bisect之前,我需要将值绑定到成员函数中.我发现很好的tutorial,并且遵循了它,但是看来我仍然做错了什么.

首先,我创建了以下课程的测试课程:

std::pair<double, double> result = bisect(&Func, 0.0, 1.0, TerminationCondition());
            double root = (result.first + result.second) / 2;

之后,我添加了绑定功能,“我认为它可以进行中”

 std::pair<double, double> result = bisect(boost::bind(&CLASS::Function,this, _1), 0.0, 1.000000, TerminationCondition());

结果是一个错误.错误:抛出’boost :: exception_detail :: clone_impl>’实例后终止调用what():函数boost :: math :: tools :: bisect中的错误:boost :: math :: tools :: bisect中的符号没有变化,或者找不到根,或者区间中有多个根(f(分钟)=-0.0032916729090909091).

无论如何,这里是class :: function,由于某种原因它不能用作具有绑定的成员函数.我以非会员身份对其进行了测试,并且可以正常工作

double CLASS::Function(double c)
{
/* values: m_a, m_b, m_c, m_d, and m_minus are located in .h file */

normal norm;
double temp = m_d*sqrt(c);

double total = ((1-boost::math::pdf(norm,(m_a*c+m_b)/temp))-(1 - m_c)+boost::math::pdf(norm,(m_a*c+m_b)/temp));

return (total - m_minus); 
}

解决方法:

如果我正确阅读了本教程,则应该是:

std::pair<double, double> result =
    bisect(boost::bind(&CLASS::Function, this, _1, _2, _3),
        0.0, 1.000000, TerminationCondition());

即boost :: bind()的参数是:

>要绑定到的函数(对象)的名称
>传递给函数的参数,因为函数期望它们

对于您的情况,是CLASS :: memberFunc(),它将是CLASS *(可能是这样,但任何CLASS *都可以),您可以照此声明,然后再将参数传递给绑定对象.

这些“未来”由_1,_2等表示,具体取决于它们在调用时的位置.

例:

class addthree {
private:
    int second;
public:
    addthree(int term2nd = 0) : second(term2nd) {}
    void addto(int &term1st, const int constval) {
        term1st += (term2nd + constval);
    }
}

int a;
addthree aa;
boost::function<void(int)> add_to_a = boost::bind(&addthree::addto, &aa, a, _1);
boost::function<void(void)> inc_a = boost::bind(&addthree::addto, &aa, a, 1);

a = 0 ; add_to_a(2); std::cout << a << std::endl;
a = 10; add_to_a(a); std::cout << a << std::endl;
a = 0 ; inc_a(); std::cout << a << std::endl;
[ ... ]

标签:c,boost,binding,bisection
来源: https://codeday.me/bug/20191014/1912418.html