你什么时候在 C++ 中使用函数对象? [英] When do you use function objects in C++?

查看:22
本文介绍了你什么时候在 C++ 中使用函数对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到函数对象经常与 STL 算法一起使用.函数对象是不是因为这些算法而产生的?你什么时候在 C++ 中使用函数对象?它有什么好处?

I see function objects used often together with STL algorithms. Did function objects came about because of these algorithms? When do you use a function object in C++? What is its benefits?

推荐答案

正如 jdv 所说,使用函子代替函数指针,函数指针更难优化和内联编译器;此外,函子的一个基本优点是它们可以轻松地在调用它们之间保持状态1,因此它们可以根据其他时间被调用而不同地工作,以某种方式跟踪它们的参数用过,...

As said jdv, functors are used instead of function pointers, that are harder to optimize and inline for the compiler; moreover, a fundamental advantage of functors is that they can easily preserve a state between calls to them1, so they can work differently depending on the other times they have been called, keep track somehow of the parameters they have used, ...

例如,如果您想对两个整数容器中的所有元素求和,您可以执行以下操作:

For example, if you want to sum all the elements in two containers of ints you may do something like this:

struct
{
    int sum;
    void operator()(int element) { sum+=element; }
} functor;
functor.sum=0;
functor = std::for_each(your_first_container.begin(), your_first_container.end(), functor);
functor = std::for_each(your_second_container.begin(), your_second_container.end(), functor);
std::cout<<"The sum of all the elements is: "<<functor.sum<<std::endl;

<小时>

  1. 实际上,正如 R Samuel Klatchko 在下面指出的那样,它们可以支持多个独立状态,每个函子实例一个:
  1. Actually, as R Samuel Klatchko pointed out below, they can support multiple independent states, one for each functor instance:
稍微更精确的说法是函子可以支持多个独立状态(函数可以通过既不是线程安全的也不是可重入的静态/全局变量).
A slightly more precise statement is that functors can support multiple independent states (functions can support a single state via statics/globals which is neither thread-safe nor reentrant).

函子使您能够使用更复杂的状态,例如共享状态(静态字段)和私有状态(实例字段).然而,很少使用这种进一步的灵活性.

Functors enables you to use even more complicated states, for example a shared state (static fields) and a private state (instance fields). However this further flexibility is rarely used.

这篇关于你什么时候在 C++ 中使用函数对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆