The template class function
is a common polymorphic function wrapper whose instances can store, copy, and invoke any callable object-functions, lambda
expressions, expressions, and bind
other function objects. It can also be a pointer to a member function pointer or a data member.
An empty function
instance call will throw an std::bad_function_call
exception.
#include <iostream>#include <functional>int main(){ std::function<intnullptr; try { f(); catch(conststd::bad_function_call& e) { std::cout‘\n‘; }}
Example code:
#include <functional>#include <iostream>structFoo {foo (intnum): num_ (num) {}voidPrint_add (intIConst{STD::cout<< Num_+i <<' \ n '; }intNum_;};voidPrint_num (inti) {STD::cout<< I <<' \ n ';}structPrintnum {void operator()(intIConst{STD::cout<< I <<' \ n '; }};intMain () {//Store a free function STD::function<void(int) > F_display = print_num; F_display (-9);//Store a lambda STD::function<void() > F_display_42 = [] () {Print_num ( the); }; F_display_42 ();//Store The result of a call to Std::bind STD::function<void() > f_display_31337 =STD:: Bind (Print_num,31337); f_display_31337 ();//Store a call to a member function STD::function<void(ConstFoo&,int) > F_add_display = &foo::p rint_add;ConstFoo Foo (314159); F_add_display (foo,1);//Store a call to a member function and object using STD::p laceholders::_1;STD::function<void(int) > F_add_display2=STD:: Bind (&foo::p rint_add, Foo/ * Caller /*, _1); F_add_display2 (2);//Store a call to a member function and object ptr STD::function<void(int) > f_add_display3=STD:: Bind (&foo::p rint_add, &foo/ * Caller /*, _1); F_add_display3 (3);//Store a call to a function object STD::function<void(int) > F_display_obj = Printnum (); F_display_obj ( -);}
Using the function object using the detailed