std::function是C++11添加的新特性之一,需要使用头文件 #include<function>
关于std::function官方说明如下:
Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.
The stored callable object is called the target of std::function. If a std::function contains no target, it is called empty. Invoking the target of an empty std::function results in std::bad_function_call exception being thrown.
std::function satisfies the requirements of CopyConstructible and CopyAssignable.
std::function是一种通用的函数包装器。模板本身,可以支持多种类型,该特性也被有的计算机从业者称为多态性。std::function可以存储、赋值和调用任何Callable目标的实例————函数、lambda表达式,绑定表达式或其他函数对象,以及成员函数和指向数据成员的指针。
样例如下:
#include<iostream>
#include<functional>
using namespace std;
void gFunc()
{
cout<<"gFunc"<<endl;
}
template <class T> T g_Add(T i, T j)
{
cout<< i + j<<endl;
return i + j;
}
auto g_Lambda = [](int i, int j)
{
return i + j;
};
struct Add
{
int operator()(int i, int j)
{
return i + j;
}
};
template<class T>
struct AddT
{
T operator()(T i, T j)
{
return i + j;
}
};
class Computer
{
public:
static int Add(int i, int j)
{
return i + j;
}
template<class T>
static T AddT(T i, T j)
{
return i + j;
}
int AddN(int i, int j)
{
return i + j;
}
};
int main(int argc, char **argv)
{
std::function<void()> f1 = gFunc;
f1();
std::function<int(int, int)> f2 = g_Add<int>;
cout<<f2(2, 3)<<endl;
std::function<int(int, int)> f3 = g_Lambda;
cout<<f3(4,6)<<endl;
std::function<int(int, int)> f4 = Add();
cout<<f4(8, 9)<<endl;
std::function<int(int, int)> ft = AddT<int>();
cout<<ft(5, 6)<<endl;
std::function<int(int, int)> f5 = &Computer::Add;
cout<< f5 (1, 2) <<endl;
std::function<int (int, int)> ftStatic = &Computer::AddT<int>;
cout<<ftStatic(2, 3)<<endl;
Computer c;
std::function<int(int, int)> fN = std::bind(&Computer::AddN, &c, placeholders::_1, placeholders::_2);
cout<< fN(1, 1) << endl;
return 0;
}