std::function是C++11添加的新特性之一,需要使用头文件 #include
关于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
#include
using namespace std;
void gFunc()
{
cout<<"gFunc"<
template
{
cout<< i + j<
}
auto g_Lambda = [](int i, int j)
{
return i + j;
};
struct Add
{
int operator()(int i, int j)
{
return i + j;
}
};
template
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
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
f1();
std::function
cout<
std::function
cout<
std::function
cout<
std::function
cout<
std::function
cout<< f5 (1, 2) <
std::function
cout<
Computer c;
std::function
cout<< fN(1, 1) << endl;
return 0;
}