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

标签 c++

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

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

这个“operator()(double 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 的匿名实例。 IE。它的工作方式与上面示例中的 f myinstance 类似,只是创建的实例没有名称。

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

关于c++ - 与圆括号和运算符()一起使用的结构名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13832709/

相关文章:

c++ - 奇怪的指针语法

c++ - 使用unique_ptr的链表的弹出方法

c++ - 无法访问特征线性系统解决方案的元素

c++ - OpenGL 和 Windows 编程 C++

c++ - 用 C++ 将数组的一部分写入文件

c++ - 如何使用 QtDbus 注册接口(interface)和注册方法?

c++ - 错误 : passing const xxx as this argument of xxx discards qualifiers

c++ - 在 OpenACC 中使用原子函数

c++ - lambda 应该衰减到模板代码中的函数指针吗?

c++ - 返回值是模板类型时如何使用std::result_of?