我看到函数对象经常与 STL 算法一起使用。函数对象的出现是因为这些算法吗?什么时候在 C++ 中使用函数对象?它有什么好处?
最佳答案
正如 jdv 所说,使用仿函数代替函数指针,后者更难为编译器优化和内联;此外,仿函数的一个基本优点是它们可以很容易地在调用它们1之间保持状态,因此它们可以根据它们被调用的其他时间以不同的方式工作,以某种方式跟踪它们的参数用过,...
例如,如果您想对两个 int 容器中的所有元素求和,您可以这样做:
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 在下面指出的那样,它们可以支持多个独立状态,每个仿函数实例一个:
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).
仿函数使您能够使用更复杂的状态,例如共享状态(静态字段)和私有(private)状态(实例字段)。然而,很少使用这种进一步的灵 active 。
关于c++ - 什么时候在 C++ 中使用函数对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2351437/