自学内容网 自学内容网

std::function的概念和使用方法

一、概念

std::function是 C++ 标准库中的一个模板类,定义在<functional>头文件中。它是一种通用的多态函数包装器,其实例能够对任何可调用对象进行存储、复制和调用操作,这些可调用对象包括普通函数、函数指针、成员函数指针、函数对象(仿函数)等,从而可以统一处理不同类型的可调用实体。

二、使用方法

1. 包含头文件

   #include <functional>

2. 包装普通函数

   #include <iostream>
   #include <functional>

   int add(int a, int b) {
       return a + b;
   }

   int main() {
       std::function<int(int, int)> func = add;
       int result = func(3, 4);
       std::cout << "Result: " << result << std::endl;
       return 0;
   }

3. 包装函数对象(仿函数)

   #include <iostream>
   #include <functional>

   struct Multiply {
       int operator()(int a, int b) const {
           return a * b;
       }
   };

   int main() {
       Multiply multiplyObj;
       std::function<int(int, int)> func = multiplyObj;
       int result = func(3, 4);
       std::cout << "Result: " << result << std::endl;
       return 0;
   }

4. 包装成员函数

   #include <iostream>
   #include <functional>

   class MyClass {
   public:
       int add(int a, int b) {
           return a + b;
       }
   };

   int main() {
       MyClass obj;
       std::function<int(MyClass*, int, int)> func = &MyClass::add;
       int result = func(&obj, 3, 4);
       std::cout << "Result: " << result << std::endl;
       return 0;
   }

5. 在容器中存储不同类型的可调用对象

   #include <iostream>
   #include <vector>
   #include <functional>

   int add(int a, int b) {
       return a + b;
   }

   struct Subtract {
       int operator()(int a, int b) const {
           return a - b;
       }
   };

   int main() {
       std::vector<std::function<int(int, int)>> funcs;
       funcs.push_back(add);
       funcs.push_back(Subtract());
       for (const auto& func : funcs) {
           int result = func(5, 3);
           std::cout << "Result: " << result << std::endl;
       }
       return 0;
   }

std::function使得代码更加灵活和可维护,它允许在运行时根据需要切换不同的可调用对象,而无需修改大量的代码。


原文地址:https://blog.csdn.net/weixin_42108533/article/details/142966450

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!