个人理解
- 声明格式:std::function<返回类型(参数类型1, 参数类型2, 参数类型3, …)>
- 适用函数类型:
- 普通函数
- 模板函数
- 匿名函数
- 函数对象(后续更新)
- 类成员函数(后续更新)
代码
main.cpp
#include<iostream>
#include<cstdio>
#include<cstring>
#include<ctime>
#include<cmath>
#include<cstdlib>
#include<windows.h>
#include<functional>
static void NormalFunc() //在函数的返回类型前面加上static表示全局的静态函数,限定在本cpp文件中使用,不能被其他cpp文件通过extern声明调用。
{
std::cout << "NormalFunc" << std::endl;
}
template<class T>
T TemplateFunc(T i, T j)
{
return i + j;
}
int num = 2;
auto LambdaFunc = [=]() -> void //目前还不知道如何extern一个Lambda表达式
{
while (num--)
{
std::cout << "LambdaFunc" << std::endl;
}
}; //匿名函数结尾要有分号
int main() {
std::function<void()> NF = NormalFunc;
std::function<int(int, int)> TF = TemplateFunc<int>; //貌似传给std::function的不能是模板函数,必须将模板实例化
std::function<void()> LF = LambdaFunc;
NF(); //输出:NormalFunc
std::cout << TF(2, 3) << std::endl; //输出:5
LF(); //输出:LambdaFunc
system("pause");
return 0;
}
输出
遗留问题
- 其实我原本是想在另外一个cpp中写上函数实现,然后在main.cpp中通过extern声明函数的,但是在声明匿名函数的时候一直报错,没有解决。
- 对于是否能以以下形式使用std::function还不太明确。
template<class T> std::function<T(T, T)> TF;
- 还有两种函数类型的使用有待补充。