与圆括号和运算符 () 一起使用的结构名称

Struct name used with round brackets and operator()

本文关键字:结构 一起 圆括号 运算符      更新时间:2023-10-16

我在BOOST中使用了一些数值积分包(见下面的代码)。任何人都可以解释以下含义:

double operator()(double x) {return x/std::log(x);}

这个"运算符()(双倍x)"是什么?

quadrature::adaptive()(f(), 0., 1., answer, error_estimate);

这里的"f()"是什么?


#include <boost/numeric/quadrature/adaptive.hpp>
#include <boost/numeric/quadrature/kronrodgauss.hpp>
#include <iostream>
#include <cmath>
namespace quadrature=boost::numeric::quadrature;
struct f
{
  double operator()(double x) const { return x/std::log(x); }
};

int main()
{
  double answer, error_estimate;
  // integrate x/log(x) on [0,1]
  quadrature::adaptive()(f(), 0., 1., answer, error_estimate);
  std::cout << "integtral(x/log(x)) on [0,1] is " << answer
            << " with error estimate " << error_estimate
            << std::endl;
  return EXIT_SUCCESS;
}

f是一个函子,即定义operator()的类(或结构,在这种情况下)。这意味着此类的实例可以像函数一样使用:

f myinstance;
myinstance(2.3);

operator()定义了f实例用作函数时的签名和行为,即它提供了将myinstance应用于参数时执行的实际函数的定义。

f()的意思是:使用默认构造函数创建f的匿名实例。 即它的工作方式与上面示例中的f myinstance类似,只是创建的实例没有名称。

如您所见,f 的实例作为参数传递给adaptive调用。在内部,此实例随后作为函数应用于各种对象。换句话说,整个机制使您能够定义一个函数(以像f这样的函子的形式)并将其作为参数传递。

operator()是C++函数调用运算符。 这意味着您可以将参数括号应用于类的对象,然后调用该运算符。

关于f(),大概这是您在下面显示的struct f的实例化。

你需要一本 C++ 教科书