std::function
头文件:<functional>
定义:
template< class R, class... Args > class function<R(Args...)>;
std::functional 是一个类模板,它是一个通用的多态函数包装器。std::funcion 的实例可以存储、拷贝、和引用任何拷贝构造的目标,函数,lambda表达式、绑定的表达式、或者其他函数对象,比如成员函数指针或者成员变量指针。
被保存的调用对象叫 std::function 调用对象。如果一个 std::function 没有包含目标,那么它被成为空。一个空的引用目标会抛出一个 std::bad_function_call 的异常。
使用实例:
#include<iostream> #include<functional> struct Foo { Foo(int num) : num_(num){} void print_add(int i) const{ // std::cout << "Foo print_add : " << "num_ + i : " << num_ + i << std::endl; std::cout << "num_ : " << num_ << ", i : " << i << " ,num_ + i : " << num_ + i << std::endl; } int num_; }; void print_num(int i) { std::cout << "print_num : " << i << "\n"; } struct PrintNum{ void operator()(int i) const { std::cout << "PrintNum operator " << i << "\n"; } }; int main() { // store a free function std::function<void(int)> f_display = print_num; f_display(-9); // store a lambda std::function<void()> f_display_2 = []() { print_num (1); }; f_display_2(); // store the result of a call to std::bind std::function<void()> f_display_3 = std::bind(print_num, 2); f_display_3(); // store a call to a member function std::function<void(const Foo&, int)> f_add_display = &Foo::print_add; const Foo foo(3); f_add_display(foo, 4); f_add_display(5,6); foo.print_add(2); // store a call to a data member accessor std::function<int(Foo const&)> f_num = &Foo::num_; std:: cout << "num_ : " << f_num(foo) << "\n"; // strore a call to a member function and object using std::placeholders::_1; std::function<void(int)> f_add_display_2 = std::bind(&Foo::print_add, foo, _1); f_add_display_2(7); // store a call to a function object std::function<void(int)> f_add_display_3 = std::bind(&Foo::print_add, &foo, _1); f_add_display_3(8); // store a call to a function object std::function<void(int)> f_display_obj = PrintNum(); f_display_obj(9); auto facotrial = [](int n) { // store a lambda object to emulate "recursive lambda"; adare of extra overhead std::function<int(int)> fac = [&](int n) { return (n < 2) ? 1 : n*fac(n-1); }; return fac(n); }; for (int i{5}; i != 8; ++i) { std::cout << i << " ! = " << facotrial(i) << "; " ; } return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2018-06-08 1071 Speech Patterns (25)(25 分)
2018-06-08 1054 The Dominant Color (20)(20 分)