使用boost::bind将成员函数绑定到boost::bisect

Using boost::bind to bind member-function to boost::bisect?

本文关键字:boost 绑定 bisect 函数 bind 使用 成员      更新时间:2023-10-16

我以前遇到过这个问题,但现在它不知怎么地工作了。

现在我有以下问题。在使用相同的函数调用boost::bisect之前,我需要将值绑定到成员函数中。我找到了一个很好的教程,我遵循了它,但似乎我仍然做错了一些事情。

首先,我创建了一个测试类,我得到以下工作:

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

之后,我添加了绑定"on the fly,因为我认为它可以工作"

 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(min) = -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()的参数为:

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

对于您的情况,一个CLASS::memberFunc(),那将是一个CLASS *(可能是this,但任何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;
[ ... ]

代码:

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

是正确的。得到的错误意味着CLASS::Function返回的是无效的。bisect在给定区间[0;1]。CLASS::Function长什么样?