C++ std::function的用法
C++ 用法 Function std
2023-09-14 09:07:06 时间
类模版std::function是一种通用、多态的函数封装。std::function的实例可以对任何可以调用的目标实体进行存储、复制、和调用操作,这些目标实体包括普通函数、Lambda表达式、函数指针、以及其它函数对象等。std::function对象是对C++中现有的可调用实体的一种类型安全的包裹(我们知道像函数指针这类可调用实体,是类型不安全的)。
通常std::function是一个函数对象类,它包装其它任意的函数对象,被包装的函数对象具有类型为T1, …,TN的N个参数,并且返回一个可转换到R类型的值。std::function使用 模板转换构造函数接收被包装的函数对象;特别是,闭包类型可以隐式地转换为std::function。
封装普通函数例子:
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <functional>
#include <memory>
using namespace std;
typedef std::function<int(int)> Functional;
int TestFunc(int a)
{
return a;
}
int main()
{
Functional obj = TestFunc;
int res = obj(1);
std::cout << res << std::endl;
while(1);
return 0;
}
封装lambda表达式 :
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <functional>
#include <memory>
using namespace std;
typedef std::function<int(int)> Functional;
auto lambda = [](int a)->int{return a;};
int main()
{
Functional obj = lambda;
res = obj(2);
std::cout << res << std::endl;
while(1);
return 0;
}
封装仿函数:
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <functional>
#include <memory>
using namespace std;
typedef std::function<int(int)> Functional;
class Functor
{
public:
int operator()(int a)
{
return a;
}
};
int main()
{
Functor func;
Functional obj = func;
res = obj(3);
std::cout << res << std::endl;
while(1);
return 0;
}
封装类的成员函数和static成员函数 :
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <functional>
#include <memory>
using namespace std;
typedef std::function<int(int)> Functional;
class CTest
{
public:
int Func(int a)
{
return a;
}
static int SFunc(int a)
{
return a;
}
};
int main()
{
CTest t;
obj = std::bind(&CTest::Func, &t, std::placeholders::_1);
res = obj(3);
cout << "member function : " << res << endl;
obj = CTest::SFunc;
res = obj(4);
cout << "static member function : " << res << endl;
while(1);
return 0;
}
关于可调用实体转换为std::function对象需要遵守以下两条原则:
1、转换后的std::function对象的参数能转换为可调用实体的参数;
2、可调用实体的返回值能转换为std::function对象的返回值。
std::function对象最大的用处就是在实现函数回调,使用者需要注意,它不能被用来检查相等或者不相等,但是可以与NULL或者nullptr进行比较。
为什么要用std::function?
好用并实用的东西才会加入标准的。因为好用,实用,我们才在项目中使用它。std::function实现了一套类型消除机制,可以统一处理不同的函数对象类型。以前我们使用函数指针来完成这些;现在我们可以使用更安全的std::function来完成这些任务。
相关文章
- C++ 类访问修饰符
- C++ map用法总结(整理)
- cout是c++还是c_c语言中cout的用法
- C++map函数的用法_random函数用法
- C++find函数用法_MATLAB中find的用法
- c++私有变量和公有变量_没有与指定类型匹配的重载函数实例
- C++ 中文周刊 第81期
- C++基本概念_c语言 c++区别
- C++ 中的预增(或预减)
- C++: 深拷贝的传统用法和现代用法
- C++STL中map容器的说明和使用技巧(杂谈)详解编程语言
- C++ tuple(STL tuple)模板用法详解
- C++ set用法(STL set用法)详解
- C++ ?:条件运算符(三目运算符)用法详解
- C++算法之海量数据处理方法的总结分析
- c++函数指针和回调函数示例
- C++采用TLS线程局部存储的用法实例
- C++实现判断字符串是否回文实例解析
- C++Vector用法深入剖析
- C++类中的static和const用法实例教程
- 浅析C/C++中sort函数的用法