C++11 function<>
何为可调用类型?
可调用类型(callable object)可以分为以下四种:
(1)传统C函数;
(2)类中的成员函数;
(3)函数对象(类中重载了“()”运算符);
(4)lambda表达式。
function<>为解决哪些问题而提出?
程序设计时,经常遇到将可调用类型作为参数传递的情况,如果针对不同的可调用类型(callable object)进行单独声明,则函数参数只能接收某种具体类型,非常不灵活。
举例:
#include <iostream>
#include<functional> //提供function模板类
//传统C函数
int c_function(int a, int b)
{
return a + b;
}
//函数对象
class Functor
{
public:
int operator()(int a, int b)
{
return a + b;
}
};
//用函数指针做参数
typedef int (*pfun)(int, int);
//函数的第一个参数只能接收函数指针
void show1(pfun f, int a, int b)
{
std::cout << f(a, b) << std::endl;
}
//用function<...>做参数
//函数第一个参数可以接收任何返回值为int,参数为int,int的可调用类型
void show2(std::function<int(int, int)> f, int a, int b)
{
std::cout << f(a, b) << std::endl;
}
int main()
{
show1(c_function, 3, 6); //输出9
//show1(Functor(), 3, 3); //编译错误,因为Functor()不能转换为函数指针
show2(c_function, 3, 5); //输出8
show2(Functor(), 3, 3); //输出6
system("pause");
}
function<>用法
#include <iostream>
#include<functional>
//测试用函数
int Minus(int a, int b)
{
return a - b;
}
//测试用类
class A
{
public:
int operator()(int a, int b)
{
return a * b;
}
void show(int a, int b)//普通成员函数
{
std::cout << a << " " << b << std::endl;
}
static void staticshow(int a, int b)//静态成员函数
{
std::cout << a << " " << b << std::endl;
}
};
int main()
{
using namespace std::placeholders;
A a;
//(1)function<>赋值类成员函数
std::function<void(A&, int, int)> f1(&A::show);
f1(a, 3, 6); //输出:3 6
//(2)function<>赋值类静态成员函数
std::function<void(int, int)> f2(&A::staticshow);
f2(6, 6);//输出:6 6
//(3)function<>赋值bind
std::function<int(int)> f3 = std::bind(Minus, 10, _1);
std::cout << f3(1) << std::endl; //输出:9
//(4)function<>赋值Lambda表达式
std::function<int(int, int)> f4 = [](int a, int b) {return a + b; };
std::cout << f4(3, 9) << std::endl; //输出:12
//(5)function<>赋值函数对象
std::function<int(int, int)> f5 = A();
std::cout << f5(6, 6) << std::endl; //输出:36
system("pause");
}
总结
使用function<…>满足了兼容所有可调用类型的需求,提高了程序设计的灵活性。