@time 2019-07-07
@author Ruo_Xiao
1、头文件
#include <functional>
2、作用
类模版 std::function
是一种通用、多态的函数封装,形成一个新的可调用的 std::function
对象。std::function
的实例可以对任何可以调用对象进行存储、复制和调用操作。std::function
对象是对 C++ 中现有的可调用实体的一种类型安全的包裹(我们知道像函数指针这类可调用实体,是类型不安全的),就是函数的容器。当我们有了函数的容器之后便能够更加方便的将函数、函数指针作为对象进行处理。
关于可调用对象的概念:对于一个对象或表达式,如果可以对其使用调用运算符,则称该对象或表达式为可调用对象。
可调用对象包括:
(1)函数。
(2)函数指针。
(3)lambda 表达式。
(4)bind 创建的对象。
(5)重载了函数调用运算符的类(仿函数)。
3、std::function 的使用有多态和万总归一的感觉,程序栗子如下:
#include <functional>
#include <iostream>
std::function<void(std::string)> Functional;
// 普通函数。
void TestFunc(std::string str)
{
std::cout << str << std::endl;
}
// Lambda表达式。
auto lambda = [](std::string str) -> void { std::cout << str << std::endl; };
// 仿函数(functor)。
class Functor
{
public:
void operator()(std::string str)
{
std::cout << str << std::endl;
}
};
// 1.类成员函数。
// 2.类静态函数。
class TestClass
{
public:
void ClassMember(std::string str)
{
std::cout << str << std::endl;
}
static void StaticMember(std::string str)
{
std::cout << str << std::endl;
}
};
int main()
{
// 普通函数。
Functional = TestFunc;
Functional("普通函数");
// Lambda表达式。
Functional = lambda;
Functional("Lambda 表达式");
// 仿函数。
Functor testFunctor;
Functional = testFunctor;
Functional("仿函数");
// 类成员函数。
TestClass testObj;
Functional = std::bind(&TestClass::ClassMember, testObj, std::placeholders::_1);
Functional("类成员函数");
// 类静态函数。
Functional = TestClass::StaticMember;
Functional("类静态函数");
return 0;
}
结果:
普通函数
Lambda 表达式
仿函数
类成员函数
类静态函数
(SAW:Game Over!)