函数对象包装器
一、std::function
Lambda表达式的本质是一个函数对象,当lambda表达式的捕获列表为空时,Lambda表达式还能作为一个函数指针进行传递:
#include <iostream>
using foo = void (int);
void functional(foo f)
{
f(1);
}
int main()
{
auto f = [](int value)
{
std::cout<<value<<std::endl;
};
functional(f); //函数指针调用
f(1); //lambda表达式调用
return 0;
}
std::function 是一种通用、多态的函数封装,它的实例可以对任何可以调用的目标实体进行存储、复制和调用操作,它也是对C++中现有的可调用实体的一种类型安全的包裹,就是函数的容器,这样可以更加方便的将函数、函数指针作为对象进行处理。例如:
#include <functional>
#include <iostream>
int foo(int para) {
return para;
}
int main() {
// std::function 包装了一个返回值为 int, 参数为 int 的函数
std::function<int(int)> func = foo;
int important = 10;
std::function<int(int)> func2 = [&](int value) -> int {
return 1+value+important;
};
std::cout << func(10) << std::endl;
std::cout << func2(10) << std::endl;
}
二、std::bind/std::placeholder
std::bind 是用来绑定函数调用的参数的,它解决的需求是:有时候可能并不一定能一次性获得调用某个函数的全部参数。通过这个函数,可以将部分调用参数提前绑定到函数身上,成为一个新的对象,然后在参数齐全后,完成调用:
#include <iostream>
#include <functional>
int foo(int a, int b, int c) {
std::cout<<a<<" "<<b<<" "<<c;
return 0;
}
int main() {
// 将参数1,2绑定到函数 foo 上,但是使用 std::placeholders::_1 来对第一个参数进行占位
auto bindFoo = std::bind(foo, std::placeholders::_1, 1,2);
// 这时调用 bindFoo 时,只需要提供第一个参数即可
bindFoo(6);
return 0;
}