你什么时候在 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;
<小时>
- 实际上,正如 R Samuel Klatchko 在下面指出的那样,它们可以支持多个独立状态,每个函子实例一个:
- 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.
相关文章