C++17新特性 函数对象包装器
#include <iostream> /*
using foo = void(int);// 使用 using 定义函数类型;Function pointer type aliasvoid functional(foo f){//定义在参数列表中的函数类型foo 被视为退化后的函数指针类型foo*f(42); // 通过函数指针调用函数
}int main() {auto f = [](int x) { std::cout << x << std::endl; }; // lambda functionfunctional(f); // 传递闭包对象,隐式转换为foo*类型的函数指针值f(100); // 直接调用 lambda 函数return 0;
}
*/
/*
上面的代码给出了两种不同的调用形式,一种是将Lambda作为函数类型传递进行调用,而另一种
则是直接调用Lambda表达式,在C++11中,统一了这些概念,将能够被调用的对象的类型,统一称之为可调用类型。
而这种类型,便是通过std::function引入的。
C++11 std::function是一种通用、多态的函数封装,它的实例可以对任何可以调用的目标实体进
行存储、复制和调用操作,它也是对中现有的可调用实体的一种类型安全的包裹(相对来说,函数
指针的调用不是类型安全的),换句话说,就是函数的容器。当我们有了函数的容器之后便能够更加方便
的将函数、函数指针作为对象进行处理。例如
*/
#include <functional> // std::function
#include <iostream>int foo(int param) {return param ;
}int main() {std::function<int(int)> func = foo; // 使用std::function定义函数容器int important = 10; // 定义一个整数变量std::function<int(int)> func2 = [&](int value) -> int { return 1+ important + value; }; std::cout << "Result: " << func(5) << std::endl; // 调用函数容器std::cout << "Result: " << func2(10) << std::endl; // 调用函数容器return 0;
}