我试图理解为什么带有构造函数的仿函数不能传递给算法,而没有构造函数的仿函数可以.
对于算法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,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"),bits);
如果我看看以前的帖子
How do C++ functor constructors get called when used with for_each or std::transform
提供的答案似乎不适用于这种情况.