在之前std::lambda表达式的例子3中,使用了一个变量来存储产生的匿名对象,当时使用的是auto:
auto func = [](const std::string &str){ return "I am listening " + str; };
这个auto推倒出来的类型其实就是std::function类型,如下:
std::function<std::string (const std::string &)> func = [](const std::string &str){ return "I am listening " + str; };
std::function是一个类模版,是一种通用的函数包装器,可以容纳所有可以调用的对象——函数(普通函数、类成员函数)、lambda表达式(上述例子)、std::bind的绑定表达式、函数对象——这些都可以通过std::function
储存、拷贝或调用。
例子:
1.function 封装 普通函数
void whatHappensToYou(string mypain) { std::cout << mypain << std::endl; } std::function<void(string)> func_whatHappensToYou = whatHappensToYou; func_whatHappensToYou("I feel sore on the back of the thigh");
2.function 封装 函数对象
class MyPain {
public:
void operator()(std::string& s) const {
std::cout << s << std::endl;
}
};
std::function<void(std::string&)> func_mypain = MyPain();
func_mypain("I feel sore on the back of the thigh");
function性能
在构造std::function时存在两个隐藏,但是可预防的开销
1. std::function构造函数按值传递被包装目标,这意味这会进行拷贝。
2. 第二个开销与被封装目标的大小有关。
了解决上面的问题,应该避免使用拷贝和大封装目标,最直接的想法是引用代替拷贝,可以用类模板 std::reference_wrapper。
为了创建std::reference_wrappers,可以使用std::ref , std::cref是用来简化非 const 和 const 的 std::reference_wrappers 的创建。
auto func = [](int val){std::cout << val + 2 << std::endl;};
std::for_each(vecInt.begin(), vecInt.end(), std::ref(func));
参考