c++ - 什么时候在 C++ 中使用函数对象?

标签 c++ stl function-object

我看到函数对象经常与 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;

  1. 实际上,正如 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/

相关文章:

c++ - 重载 "function call"运算符有什么用?

c++ - 多态中的函数对象

c++ - FBX SDK 骨骼动画

c++ - Visual Studio C++ : Getting Unresolved tokens and unresolved link. 我该怎么办?

c++ - 从 C 程序访问 C++ 函数时,收到错误消息 "Access violation reading location"

iphone - Objective-C 中 C++ STL 容器 "pair<T1, T2>"的等价物?

c++ - 使用 WMI (c++) 枚举工作组中的 pc

c++ - 我可以将 auto_ptr 放入 STL 容器中吗?

c++ - 为什么 std::shared_ptr<T> = std::unique_ptr<T[]> 编译,而 std::shared_ptr<T[]> = std::unique_ptr<T[]> 不编译?

c++ - 函数对象的正确参数类型是什么?