什么时候在C ++中使用函数对象? [英] When do you use function objects in 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, ...
例如,如果要对int的两个容器中的所有元素求和,您可以这样做:
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在下面指出,他们可以支持多个独立状态,每个functor实例一个:
- 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允许您使用更复杂的状态,例如共享状态(静态字段)和私有状态(实例字段)。但是,这种进一步的灵活性很少使用。
这篇关于什么时候在C ++中使用函数对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!