c++ - 我如何构造一个仿函数以用于像 boost 的 brent_find_minima 这样的算法?

标签 c++ algorithm boost constructor functor

我试图理解为什么不能将具有构造函数的仿函数传递给算法,而没有构造函数的仿函数却可以。

对于算法 boost-brent_minima。 当仿函数没有构造函数时,示例代码工作正常:

#include <boost/math/tools/minima.hpp>

struct funcdouble
{
  double operator()(double const& x)
  { //
    return (x + 3) * (x - 1) * (x - 1); // (x + 3)(x - 1)^2
  }
};

int bits = std::numeric_limits<double>::digits;

std::pair<double, double> r = brent_find_minima(funcdouble(), -4., 4. / 3, bits);

std::cout.precision(std::numeric_limits<double>::digits10);
std::cout << "x at minimum = " << r.first << ", f(" << r.first << ") = " << r.second << std::endl;

但是,当我使用构造函数生成这样的自定义仿函数时:

struct solver_test{

    solver_test::solver_test(std::string expression_string, std::string x_name_) : x_name(x_name_){
        symbol_table.add_constants();       
        symbol_table.create_variable(x_name);
        expression.register_symbol_table(symbol_table);     
        parser.compile(expression_string, expression);
    };

    double operator()(double x) {
        symbol_table.get_variable(x_name)->ref() = x;
        double value = expression.value();
        return value;
    };

    std::string x_name;
    exprtk::symbol_table<double> symbol_table;
    exprtk::expression<double> expression;
    exprtk::parser<double> parser;

};

int bits = std::numeric_limits<double>::digits;

solver_test test_root_finder("(x + 3)(x - 1)^2", "x");
std::pair<double, double> r = boost::math::tools::brent_find_minima(test_root_finder, -4., 4. / 3, bits);

std::cout.precision(std::numeric_limits<double>::digits10);
std::cout << "x at minimum = " << r.first << ", f(" << r.first << ") = " << r.second << std::endl;

我收到编译器错误 C2280 - 在 brent_find_minima 行上引用已删除的函数。尝试时也会出现此错误:

std::pair<double, double> r = boost::math::tools::brent_find_minima(solver_test("(x + 3)(x - 1)^2", "x"), -4., 4. / 3, bits);

如何在不事先实例化的情况下使用构造函数传递仿函数?

如果我看以前的帖子

How do C++ functor constructors get called when used with for_each or std::transform

提供的答案似乎不适用于此案例。

最佳答案

如果我尝试,问题就会变得清晰

solver_test test_root_finder("(x + 3)(x - 1)^2", "x");
solver_test copy_test = test_root_finder;

因为仿函数没有复制构造函数,所以它不能像这样传递给算法:

std::pair<double, double> r = boost::math::tools::brent_find_minima(test_root_finder, -4., 4. / 3, bits);

添加

solver_test::solver_test(const solver_test &obj) {};

让一切正常。

关于c++ - 我如何构造一个仿函数以用于像 boost 的 brent_find_minima 这样的算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40008674/

相关文章:

C++ 继承的模板类无权访问基类

algorithm - 遍历所有区域的最短路径

c++ - 高度并行的双端队列

c++ - DirectX 11 着色器资源管理

c++ - 有没有办法使用特征使 pos_type 和 off_type 成为 int64_t?

algorithm - 能力之谜

algorithm - 给定一组条件,通过算法确定只有一个可以为真

c++ - 如何使 boost::serialization 与 std::shared_ptr 一起工作?

python - 使用 boost::numpy 时出现 LNK2001 错误

c++ - ISO C 中数组的左值到右值转换